import pandas as pd
subjects = {
"name": ["Math", "Physics", "Chemistry", "English", "Hindi"],
"score": [98, 91, 78, 80, 76],
"code": ["M01", "P02", "C04", "E02", "H08"]
}
# Create the dataframe
df = pd.DataFrame(subjects)
print(df)
# Delete a column
df = df.drop(columns=['name'])
print(df)
Output
name score code
0 Math 98 M01
1 Physics 91 P02
2 Chemistry 78 C04
3 English 80 E02
4 Hindi 76 H08
score code
0 98 M01
1 91 P02
2 78 C04
3 80 E02
4 76 H08
The drop() function of Pandas Dataframe can be used to delete single or multiple columns from the Dataframe. You can pass the column names array in it and it will remove the columns based on that.
Syntax
df.drop(columns=["COUMN_NAME_1", "COUMN_NAME_2"])
Remove single column from Dataframe
import pandas as pd
subjects = {
"name": ["Math", "Physics", "Chemistry", "English", "Hindi"],
"score": [98, 91, 78, 80, 76],
"code": ["M01", "P02", "C04", "E02", "H08"]
}
# Create the dataframe
df = pd.DataFrame(subjects)
print(df)
# Delete a column
df = df.drop(columns=['score'])
print(df)
Output
name score code
0 Math 98 M01
1 Physics 91 P02
2 Chemistry 78 C04
3 English 80 E02
4 Hindi 76 H08
name code
0 Math M01
1 Physics P02
2 Chemistry C04
3 English E02
4 Hindi H08
Remove multiple columns from Dataframe
import pandas as pd
subjects = {
"name": ["Math", "Physics", "Chemistry", "English", "Hindi"],
"score": [98, 91, 78, 80, 76],
"code": ["M01", "P02", "C04", "E02", "H08"]
}
# Create the dataframe
df = pd.DataFrame(subjects)
# Delete two column
df = df.drop(columns=['name', 'score'])
print(df)
Output
code
0 M01
1 P02
2 C04
3 E02
4 H08
If you do not want to reassign Dataframe, you can use inplace=True in the drop() function.
df.drop(columns=['name', 'score'], inplace=True)
The del keyword can also be used to delete a column from Pandas Dataframe. You need to place the del keyword before the Dataframe variable along with the column name that you want to delete.
Syntax
del df['COLUMN_NAME']
Code Example
import pandas as pd
data = {
"column 1": [10, 20, 30, 40],
"column 2": ['a', 'b', 'c', 'd'],
"column 3": [1, 2, 3, 4]
}
df = pd.DataFrame(data)
del df['column 3']
print(df)
Output
column 1 column 2
0 10 a
1 20 b
2 30 c
3 40 d
Using the above code example, we have removed "column 3" from the Dataframe using del keyword
import pandas as pd
data = {
"column 1": [5, 10, 15, 20],
"column 2": ['a', 'b', 'c', 'd'],
"column 3": [1, 2, 3, 4]
}
df = pd.DataFrame(data)
df.pop('column 1')
print(df)
# column 2 column 3
# 0 a 1
# 1 b 2
# 2 c 3
# 3 d 4
0 Comments