drop column pandas in python

You can drop columns from pandas dataframe using the drop() method.

You can drop a single column or multiple columns by passing column names as a string or list of strings to the drop() method.

Here is the code to drop a single column:

main.py
import pandas as pd

# create dataframe
df = pd.DataFrame({'Name':['John', 'Sam', 'David'],
                   'Age':[32, 25, 19],
                   'City':['New York', 'London', 'Paris']})

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

print(df)
253 chars
12 lines

Output:

main.py
    Name  Age
0   John   32
1    Sam   25
2  David   19
56 chars
5 lines

Here is the code to drop multiple columns:

main.py
import pandas as pd

# create dataframe
df = pd.DataFrame({'Name':['John', 'Sam', 'David'],
                   'Age':[32, 25, 19],
                   'City':['New York', 'London', 'Paris']})

# drop columns 'Age' and 'City'
df = df.drop(['Age', 'City'], axis=1)

print(df)
273 chars
12 lines

Output:

main.py
    Name
0   John
1    Sam
2  David
36 chars
5 lines

related categories

gistlibby LogSnag