How to Delete a Column From a Pandas Dataframe?


To delete a column from a pandas dataframe, you can use the drop method. Here's an example:

import pandas as pd

# create a dataframe
data = {'Name': ['John', 'Mary', 'Peter'],
        'Age': [32, 25, 47],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)

# print the dataframe

# delete the 'City' column
df = df.drop('City', axis=1)

# print the dataframe after the column is deleted


    Name  Age         City
0   John   32     New York
1   Mary   25  Los Angeles
2  Peter   47      Chicago

    Name  Age
0   John   32
1   Mary   25
2  Peter   47

In the drop method, we specify the column name that we want to delete, and we set axis=1 to delete a column (by default, axis=0 is used to delete rows).

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?