Pandas Tutorial: How to delete a column of data in a DataFrame?
As the demand for data analysis continues to increase, Python's Pandas library has become one of the important tools for data analysts. Pandas provides powerful data manipulation and processing functions. One common operation is to delete a certain column of data in a DataFrame. This article will introduce in detail how to use Pandas to delete a column of data in a DataFrame and provide specific code examples.
Before starting, you first need to install the Pandas library. Pandas can be installed in a Python environment using the following command:
pip install pandas
After the installation is complete, the Pandas library can be imported through the following code:
import pandas as pd
Next, we will use a sample DataFrame to demonstrate deleting columns operation. Suppose we have a DataFrame named data
, containing the following data:
A B C D 0 1 2 3 4 1 5 6 7 8 2 9 10 11 12
Now, we want to delete column C. You can use the drop
method to achieve this goal. The drop
method accepts a parameter labels
, which is used to specify the labels (column names) to be deleted, and returns a new DataFrame.
The following is a code example to delete column C:
data = pd.DataFrame({'A': [1, 5, 9], 'B': [2, 6, 10], 'C': [3, 7, 11], 'D': [4, 8, 12]}) data = data.drop('C', axis=1)
In this example, we first create a file named data# using the
pd.DataFrame method ##DataFrame, and then use the
drop method to delete column C. Note that we use the
axis=1 parameter to specify the column to delete. If the
axis parameter is not specified, rows will be deleted by default.
data will become as follows:
A B D 0 1 2 4 1 5 6 8 2 9 10 12
drop method, you can also use Python The
del keyword to delete columns. The following is a code example that uses the
del keyword to delete column C:
data = pd.DataFrame({'A': [1, 5, 9], 'B': [2, 6, 10], 'C': [3, 7, 11], 'D': [4, 8, 12]}) del data['C']
data will become the following:
A B D 0 1 2 4 1 5 6 8 2 9 10 12
pop method to delete columns and return the deleted columns. The following is a code example to delete column C using the
pop method:
data = pd.DataFrame({'A': [1, 5, 9], 'B': [2, 6, 10], 'C': [3, 7, 11], 'D': [4, 8, 12]}) C_column = data.pop('C')
C_column will save the contents of the deleted column C. After deleting the column, the contents of
data are the same as in the previous example.
drop method,
del keyword and
pop method, you can easily delete the specified column and return a new DataFrame or the deleted column.
The above is the detailed content of Learn to use Pandas: How to delete a column of data in a DataFrame. For more information, please follow other related articles on the PHP Chinese website!