Removing rows using integer index in Pandas DataFrame
Start your free 7-days trial now!
Solution
To remove rows using integer index in Pandas DataFrame:
Removing a single row using integer index
Consider the following DataFrame:
df = pd.DataFrame({"A":[2,3,4],"B":[5,6,7]}, index=["a","b","c"])df
A Ba 2 5b 3 6c 4 7
To remove row at integer index 1:
df.drop(index=df.iloc[1].name)
A Ba 2 5c 4 7
Explanation
The drop(~) method is used to remove rows and columns, but the caveat is that you can only remove rows/column by their name. Therefore, we first use iloc to extract the row at integer index 1, and then extract its name using the name property:
df.iloc[1].name
'b'
The drop(~) method returns a new DataFrame, that is, the original df is kept intact. To directly modify the original df, set inplace=True.
Removing multiple rows using integer index
Consider the same df as above:
df = pd.DataFrame({"A":[2,3,4],"B":[5,6,7]}, index=["a","b","c"])df
A Ba 2 5b 3 6c 4 7
To remove multiple rows at integer index 0 and 1:
df.drop(index=df.iloc[[0,1]].index)
A Bc 4 7
Explanation
We first extract rows at integer index 0 and 1 as a DataFrame using iloc:
df.iloc[[0,1]]
A Ba 2 5b 3 6
We then fetch the index of this DataFrame using the index property:
df.iloc[[0,1]].index
Index(['a', 'b'], dtype='object')
Now that we have the labels of the rows that we want to remove, directly pass this into drop(~):
df.drop(index=df.iloc[[0,1]].index)
A Bc 4 7