Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dataframe pandas drop column using int

I understand that to drop a column you use df.drop('column name', axis=1). Is there a way to drop a column using a numerical index instead of the column name?

like image 415
user1802143 Avatar asked Nov 30 '13 06:11

user1802143


People also ask

How do I delete a column by index number?

You can drop columns by index by using DataFrame. drop() method and by using DataFrame. iloc[].

How do I drop a specific value in pandas?

Method 1: Drop the specific value by using Operators We can use the column_name function along with the operator to drop the specific value.


2 Answers

You can delete column on i index like this:

df.drop(df.columns[i], axis=1) 

It could work strange, if you have duplicate names in columns, so to do this you can rename column you want to delete column by new name. Or you can reassign DataFrame like this:

df = df.iloc[:, [j for j, c in enumerate(df.columns) if j != i]] 
like image 160
Roman Pekar Avatar answered Sep 28 '22 07:09

Roman Pekar


Drop multiple columns like this:

cols = [1,2,4,5,12] df.drop(df.columns[cols],axis=1,inplace=True) 

inplace=True is used to make the changes in the dataframe itself without doing the column dropping on a copy of the data frame. If you need to keep your original intact, use:

df_after_dropping = df.drop(df.columns[cols],axis=1) 
like image 25
muon Avatar answered Sep 28 '22 07:09

muon