How to implement column deletion operation in PythonPandas

尊渡假赌尊渡假赌尊渡假赌
Release: 2023-12-19 11:53:34
Original
934 people have browsed it

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.

How to implement column deletion operation in PythonPandas

# 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:

  1. Import the Pandas module:
import pandas as pd
Copy after login
  1. Create a DataFrame:
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
Copy after login
  1. Use drop () method deletes the specified column:
df = df.drop('age', axis=1)
print(df)
# 输出:
#        name gender
# 0     Alice      F
# 1       Bob      M
# 2   Charlie      M
Copy after login

axis=1 here means operating by column.

  1. If you want to delete multiple columns at the same time, you can pass a list of column names:
df = df.drop(['age', 'gender'], axis=1)
print(df)
# 输出:
#        name
# 0     Alice
# 1       Bob
# 2   Charlie
Copy after login
  1. Also, you can also directly use the column index to delete columns. For example, in the above DataFrame, if you need to delete the second column (i.e. age column), you can use the following code:
df = df.drop(df.columns[1], axis=1)
print(df)
# 输出:
#        name gender
# 0     Alice      F
# 1       Bob      M
# 2   Charlie      M
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template