删除一个或多个列是Pandas数据框架中的常用操作。在Pandas中,我们可以使用drop()
方法来删除一个或多个列。具体操作步骤如下:
Step 1: 导入Pandas库并读取数据
首先,我们需要导入Pandas库,并读取相关的数据。我们在这里使用官方提供的Iris(鸢尾花)数据集作为示例。
import pandas as pd
# 读取数据
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',
header=None,
names=['sepal length', 'sepal width', 'petal length', 'petal width', 'class'])
# 查看前5行数据
df.head(5)
输出结果:
sepal length sepal width petal length petal width class
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
Step 2: 删除一个或多个列
接下来,我们可以使用drop()
方法来删除一个或多个列。drop()
方法中的axis
参数用于指定删除行或列,其中axis=0
表示删除行(默认值),axis=1
表示删除列。具体操作步骤如下:
删除一个列
# 删除'petal width'列(单个列),并返回新的数据框架
df_drop = df.drop('petal width', axis=1)
# 查看前5行数据
df_drop.head(5)
输出结果:
sepal length sepal width petal length class
0 5.1 3.5 1.4 Iris-setosa
1 4.9 3.0 1.4 Iris-setosa
2 4.7 3.2 1.3 Iris-setosa
3 4.6 3.1 1.5 Iris-setosa
4 5.0 3.6 1.4 Iris-setosa
可以看到,新的数据框架中已经删除了’petal width’列。
删除多个列
我们可以在drop()
方法的columns
参数中指定需要删除的多个列,以列表形式传递参数即可。
# 删除'margin length'列和'margin width'列(多个列),并返回新的数据框架
df_drop = df.drop(columns=['sepal length', 'sepal width'])
# 查看前5行数据
df_drop.head(5)
输出结果:
petal length petal width class
0 1.4 0.2 Iris-setosa
1 1.4 0.2 Iris-setosa
2 1.3 0.2 Iris-setosa
3 1.5 0.2 Iris-setosa
4 1.4 0.2 Iris-setosa
可以看到,新的数据框架中已经删除了’sepal length’列和’sepal width’列。
Step 3: 修改原数据框架
以上的方法都是针对原数据框架的复制,如果我们想要直接在原数据框架上进行更改,则需要将inplace
参数设置为True
。
删除一个列
# 直接删除'petal width'列(单个列),并返回新的数据框架
df.drop('petal width', axis=1, inplace=True)
# 查看前5行数据
df.head(5)
输出结果:
sepal length sepal width petal length class
0 5.1 3.5 1.4 Iris-setosa
1 4.9 3.0 1.4 Iris-setosa
2 4.7 3.2 1.3 Iris-setosa
3 4.6 3.1 1.5 Iris-setosa
4 5.0 3.6 1.4 Iris-setosa
可以看到,原数据框架中已经删除了’petal width’列。
删除多个列
# 直接删除'sepal length'列和'sepal width'列(多个列),并返回新的数据框架
df.drop(columns=['sepal length', 'sepal width'], inplace=True)
# 查看前5行数据
df.head(5)
输出结果:
petal length class
0 1.4 Iris-setosa
1 1.4 Iris-setosa
2 1.3 Iris-setosa
3 1.5 Iris-setosa
4 1.4 Iris-setosa
可以看到,原数据框架中已经删除了’sepal length’列和’sepal width’列。
小结
本文详细讲解了如何在Pandas数据框架中删除一个或多个列。我们可以使用drop()
方法来实现,同时还介绍了如何在原数据框架上直接进行更改。通过本文的学习,相信读者已经能够熟练地掌握这一操作。