Concise Guide: How to delete specific columns using Pandas requires specific code examples
In data analysis and processing, Pandas is a commonly used tool that provides Powerful data structure and data manipulation functions. When processing data, we often need to delete unnecessary columns. This article will introduce how to delete specific columns using Pandas and provide specific code examples.
Before you begin, make sure you have the Pandas library installed. It can be installed using the following command:
pip install pandas
First, we need to import the Pandas library and introduce its common alias pd:
import pandas as pd
Next, we create a sample data set to demonstrate the removal of specific Column method:
data = {'Name': ['Tom', 'Nick', 'John'], 'Age': [20, 21, 22], 'City': ['New York', 'Los Angeles', 'Chicago']} df = pd.DataFrame(data) print(df)
Running the above code, we get the following output:
Name Age City 0 Tom 20 New York 1 Nick 21 Los Angeles 2 John 22 Chicago
Now, we can use Pandas’ drop()
method to drop a specific column. drop()
The method accepts a parameter columns
, which is used to specify the columns that need to be deleted. Here are some common ways to delete columns.
We can delete columns directly through column names. The following is a sample code:
df = df.drop(columns=['Age']) print(df)
The output result is:
Name City 0 Tom New York 1 Nick Los Angeles 2 John Chicago
In addition to using column names, we can also delete columns by column index. Here is the sample code:
df = df.drop(df.columns[1], axis=1) print(df)
The output is:
Name City 0 Tom New York 1 Nick Los Angeles 2 John Chicago
In this example, we deleted the column with index 1 (note that the index starts counting from 0).
If you want to delete multiple columns, we can pass in a parameter containing multiple column names (or column indexes) in the columns
parameter list of. The following is the sample code:
df = df.drop(columns=['Age', 'City']) print(df)
The output is:
Name 0 Tom 1 Nick 2 John
In this example, we have deleted both columns 'Age' and 'City'.
To summarize, by using Pandas’ drop()
method, we can easily delete specific columns. The operation can be done using column names or column indexes as needed, and one or more columns can be deleted.
I hope the code examples provided in this article can help you better master the method of deleting specific columns in Pandas. By applying these methods flexibly, you can process and analyze data more efficiently.
The above is the detailed content of Pandas easy way: delete specified column operation. For more information, please follow other related articles on the PHP Chinese website!