To delete a column from a Pandas DataFrame, you can use the ‘DataFrame.drop()
‘method. This method takes a list of labels and an axis (either ‘0
‘ or ‘1
‘) as arguments, and it returns a new DataFrame with the specified columns or rows removed.
Here’s an example of how you can use ‘drop()
‘ to delete a column from a DataFrame:
import pandas as pd
# Load a sample DataFrame
df = pd.read_csv("data.csv")
# Drop the "col_2" column
df = df.drop(columns=["col_2"])
# Print the DataFrame with the "col_2" column removed
print(df)
You can also use the ‘inplace
‘ parameter to update the DataFrame in place, without creating a new DataFrame:
import pandas as pd
# Load a sample DataFrame
df = pd.read_csv("data.csv")
# Drop the "col_2" column in place
df.drop(columns=["col_2"], inplace=True)
# Print the DataFrame with the "col_2" column removed
print(df)
Keep in mind that the ‘drop()
‘ method works with the column labels, not the column names. If you want to delete a column by its actual name, you can use the ‘del
‘keyword:
import pandas as pd
# Load a sample DataFrame
df = pd.read_csv("data.csv")
# Delete the "col_2" column
del df["col_2"]
# Print the DataFrame with the "col_2" column removed
print(df)
This will delete the “col_2” column from the DataFrame in place.
RELATED : Renaming column names in Pandas