Delete a column from a Pandas DataFrame
You can delete a column from a Pandas DataFrame using the drop function. This function returns a new DataFrame with the specified column(s) removed. It takes two main arguments: labels and axis.
labels: a single label or a list of labels to remove.
axis: specifies whether you are referring to rows or columns. axis=0 refers to rows, and axis=1 refers to columns.
Here's an example of how to use drop to delete a column from a DataFrame:
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]})
# Print the DataFrame
print(df)
# col1 col2 col3
# 0 1 4 7
# 1 2 5 8
# 2 3 6 9
# Delete the 'col2' column
df = df.drop('col2', axis=1)
# Print the DataFrame
print(df)
# col1 col3
# 0 1 7
# 1 2 8
# 2 3 9Note that this operation returns a new DataFrame with the column removed. If you want to modify the original DataFrame in place, you can use the inplace parameter. For example:
df.drop('col1', axis=1, inplace=True)This will delete the 'col1' column from the df DataFrame and modify df in place.