How to drop a row using iloc method

Viewed 20083

I dropped the first two columns using the iloc method in the following code without any problem.

eng_df.drop(eng_df.iloc[:,:2] , axis=1, inplace=True)

But I tried to delete the first row with the iloc method in the following code and it did not work:

eng_df.drop(eng_df.iloc[:1 , :] ,  inplace=True)

... and get the following warning:

KeyError: "['Country' 'Energy Supply' 'Energy Supply per Capita' '% Renewable'] not found in axis"

I know I can drop the row in different ways, but my question is can I drop rows with the iloc method, if so, how can I do that and what is wrong in my codes? Thanks...

4 Answers

As per documentation of, pandas.DataFrame.drop

Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level.

So, for your code,

# dropping columns
eng_df.drop(columns=eng_df.iloc[:,:2].columns.tolist(), inplace=True)

# dropping index
eng_df.drop(index=eng_df.iloc[:1, :].index.tolist(), inplace=True)

This worked for me for dropping just one row:

dfcombo.drop(dfcombo.iloc[4].name)

Use iloc to get the row as a Series, then get the row's index as the 'name' attribute of the Series. Then use the index to drop.

For your example I guess it would be:

eng_df.drop(eng_df.iloc[0].name,  inplace=True)

Try to add .index: df_train_corr.drop(df_train_corr.iloc[1::2].index, inplace=True). This code deletes all odd rows.

With pandas version 0.22.0 I believe this would work.

#to drop iloc 104
eng_df.drop(labels=104, inplace=True)
Related