In Pandas, you can use the "drop()" method to delete columns in the DataFrame: 1. Use "import pandas as pd" to import the Pandas module; 2. Create a DataFrame; 3. Use "drop( )" method to delete specified columns; 4. You can pass a list of column names to delete multiple columns at the same time; 5. Directly use the column index to delete columns.
# Operating system for this tutorial: Windows 10 system, Dell G3 computer.
In Pandas, you can use the drop() method to delete columns in a DataFrame. The specific steps are as follows:
import pandas as pd
data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'gender': ['F', 'M', 'M']} df = pd.DataFrame(data) print(df) # 输出: # name age gender # 0 Alice 25 F # 1 Bob 30 M # 2 Charlie 35 M
df = df.drop('age', axis=1) print(df) # 输出: # name gender # 0 Alice F # 1 Bob M # 2 Charlie M
axis=1 here means operating by column.
df = df.drop(['age', 'gender'], axis=1) print(df) # 输出: # name # 0 Alice # 1 Bob # 2 Charlie
df = df.drop(df.columns[1], axis=1) print(df) # 输出: # name gender # 0 Alice F # 1 Bob M # 2 Charlie M
Note that the drop() method returns a new DataFrame, the original DataFrame will not be modified. If you want to make modifications on the original DataFrame, you can use the inplace=True parameter:
df.drop('age', axis=1, inplace=True)
Hope this helps you understand how to delete columns in Pandas! If you have any other questions, please feel free to ask.
The above is the detailed content of How to implement column deletion operation in PythonPandas. For more information, please follow other related articles on the PHP Chinese website!