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?
You can drop columns by index by using DataFrame. drop() method and by using DataFrame. iloc[].
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.
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]]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With