Pandas DataFrame | drop method
Start your free 7-days trial now!
Pandas's DataFrame.drop(~) method returns a DataFrame with the specified columns/rows removed.
Parameters
1. labels | string or list<string> | optional
The name(s) of the index or column to remove.
2. axis | int or string | optional
Whether to remove columns or rows:
Axis | Meaning |
|---|---|
| Removes rows |
| Removes columns |
By default, axis=0.
3. indexlink | string or list<string> | optional
The name(s) of the index to remove. This is equivalent to specifying parameters axis=0 and labels.
4. columnslink | string or list<string> | optional
The name(s) of the columns you want to remove. This is equivalent to specifying parameters axis=1 and labels.
5. inplacelink | boolean | optional
If
True, then the method will directly modify the source DataFrame instead of creating a new DataFrame.If
False, then a new DataFrame will be created and returned.
By default, inplace=False.
For clarity, specify the parameters index or columns instead of specifying labels and axis - the code is shorter and clearer.
Return Value
A DataFrame with the specified columns/rows removed. If inplace=True, then the return type is None since the source DataFrame is directly modified.
Examples
Dropping columns
Consider the following DataFrame:
df
A B C0 1 3 51 2 4 6
Dropping a single column
To delete column A only:
df.drop(columns="A")
B C0 3 51 4 6
This is equivalent to the following code:
df.drop(labels="A", axis=1) # This is not the preferred way since the intention is unclear.
Note that since inplace=False, the original df is left intact.
Dropping multiple columns
To delete columns A and B:
df.drop(columns=["A","B"])
C0 51 6
This is equivalent to the following code:
df.drop(labels=["A","B"], axis=1) # This is not the preferred way since the intention is unclear.
C0 51 6
Dropping rows
Consider the following DataFrame:
df
A B C0 1 4 71 2 5 82 3 6 9
Dropping a single row
To drop the second row (i.e. row with index=1):
df.drop(index=1)
A B C0 1 4 72 3 6 9
This is equivalent to the following code:
df.drop(labels=[1], axis=0) # This is not the preferred way.
A B C0 1 4 72 3 6 9
Dropping multiple rows
To drop the first two rows (i.e. rows with index=0 and index=1):
df.drop(index=[0, 1])
A B C2 3 6 9
This is equivalent to the following code:
df.drop(labels=[0,1], axis=0) # This is not the preferred way.
A B C2 3 6 9
Dropping in-place
To drop row(s) or column(s) in-place, we need to set inplace=True. What this does is that the drop(~) method will directly modify the source DataFrame instead of creating and returning a new DataFrame.
As an example, consider the following DataFrame:
df
A B C0 1 3 51 2 4 6
We then drop columns A and B with inplace=True:
df.drop(columns=["A", "B"], inplace=True)df
C0 51 6
As shown in the output, the source DataFrame has been modified.