目录
在操作数据的时候, DataFrame 对象中删除一个或多个列是常见的操作,并且实现方法较多,然而这中间有很多细节值得关注。
首先,一般被认为是“正确”的方法,是使用 DataFrame 的 drop 方法,之所以这种方法被认为是标准的方法,可能是收到了 SQL 语句中使用 drop 实现删除操作的影响。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(25).reshape((5,5)), columns=list("abcde"))
display(df)
try:
df.drop('b')
except KeyError as ke:
print(ke)
输出:
a b c d e
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
4 20 21 22 23 24
"['b'] not found in axis"
上面的操作中出现了报错信息,什么原因?这是因为 drop 方法中,默认是删除行。
如果用 axis=0
或 axis='rows'
,都表示展出行,也可用 labels 参数删除行。
df.drop(0) # drop a row, on axis 0 or 'rows'
df.drop(0, axis=0) # same
df.drop(0, axis='rows') # same
df.drop(labels=0) # same
df.drop(labels=[0]) # same
# 结果
a b c d e
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
4 20 21 22 23 24