how to drop a column in pandas

2 hours ago 2
Nature

To drop a column in a pandas DataFrame, you typically use the drop() method with the column name and specify the axis as 1 (since columns are on axis 1). Here are the common ways to do it:

  • Drop a single column by name and return a new DataFrame:

    python

    df = df.drop('column_name', axis=1)

  • Drop multiple columns by passing a list of column names:

    python

    df = df.drop(['col1', 'col2'], axis=1)

  • Drop a column in-place without creating a new DataFrame:

    python

    df.drop('column_name', axis=1, inplace=True)

  • Alternatively, you can use the columns keyword instead of axis:

    python

    df = df.drop(columns=['column_name'])

  • You can also delete a column using the del keyword:

    python

    del df['column_name']

Note that del df.column_name does not work for deleting columns, even though you can access columns that way

. In summary, the most common and versatile method is:

python

df.drop('column_name', axis=1, inplace=True)

to remove a column directly from the DataFrame