How To Remove Columns From DataFrame ?
Table Of Contents:
- Syntax ‘pop()’ Method In Pandas.
- Examples ‘pop( )’ Method.
(1) Syntax:
DataFrame.drop(labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise'
Description:
- Drop specified labels from rows or columns.
- Remove rows or columns by specifying label names and corresponding axis, or by specifying direct index or column names.
- When using a multi-index, labels on different levels can be removed by specifying the level. See the user guide <advanced.shown_levels> for more information about the now unused levels.
Parameters:
- labels : single label or list-like –
- Index or column labels to drop. A tuple will be used as a single label and not treated as a list-like.
- axis: {0 or ‘index’, 1 or ‘columns’}, default 0 –
- Whether to drop labels from the index (0 or ‘index’) or columns (1 or ‘columns’).
- If you don’t mention anything it will search for the index not the column.
- index: single label or list-like –
- Alternative to specifying axis (
labels, axis=0
is equivalent toindex=labels
).
- Alternative to specifying axis (
- columns: single label or list-like –
- Alternative to specifying axis (
labels, axis=1
is equivalent tocolumns=labels
).
- Alternative to specifying axis (
- level: int or level name, optional –
- For MultiIndex, level from which the labels will be removed.
- in place: bool, default False –
- If False, return a copy. Otherwise, do operation inplace and return None.
- errors: {‘ignore’, ‘raise’}, default ‘raise’ –
- If ‘ignore’, suppress error and only existing labels are dropped.
Returns:
- DataFrame or None – DataFrame without the removed index or column labels or None if
inplace=True
.
Raises:
- KeyError – If any of the labels is not found in the selected axis.
(2) Examples Of drop() Method:
Example-1
import pandas as pd
student = {'Name':['Subrat','Abhispa','Arpita','Anuradha','Namita'],
'Roll_No':[100,101,102,103,104],
'Subject':['Math','English','Science','History','Commerce'],
'Mark':[95,88,76,73,93],
'Gender':['Male','Female','Female','Female','Female']}
student_object = pd.DataFrame(student)
student_object
Output:
# Dropping The ‘Subject’ Column.
student_object.drop(['Subject'],axis='columns')
Output:
# Dropping Row Number 1.
student_object.drop([1],axis='index')
Output:
# Changing The Original DataFrame
student_object.drop(['Roll_No'],axis='columns',inplace=True)
student_object
Output:
Note:
- If we put ‘inplace = True’ then, the original DataFrme will be updated.
# Dropping The ‘Subject’ Column.
student_object.drop(['Subject'])
Output:
KeyError Traceback (most recent call last)
Input In [505], in <cell line: 1>()
----> 1 student_object.drop(['Subject'])
KeyError: "['Subject'] not found in axis"
Note:
- By default, it will try to drop from the row index, if the row index does not fount, it will raise ‘Keyerror’.