To delete a column in a DataFrame, I can successfully use:
del df['column_name']
But why can't I use the following?
del df.column_name
Since it is possible to access the Series via df.column_name
, I expected this to work.
dataframedelpandaspython
To delete a column in a DataFrame, I can successfully use:
del df['column_name']
But why can't I use the following?
del df.column_name
Since it is possible to access the Series via df.column_name
, I expected this to work.
Best Answer
The best way to do this in Pandas is to use
drop
:where
1
is the axis number (0
for rows and1
for columns.)Or, the
drop()
method acceptsindex
/columns
keywords as an alternative to specifying the axis. So we can now just do:To delete the column without having to reassign
df
you can do:Finally, to drop by column number instead of by column label, try this to delete, e.g. the 1st, 2nd and 4th columns:
Also working with "text" syntax for the columns: