当对drop
使用pandas.DataFrame
方法时,它接受列名列表,但不接受元组,尽管documentation表示“类列表”参数是可接受的。我是否读错了文档,因为我希望我的MWE能正常工作。
MWE公司
import pandas as pd
df = pd.DataFrame({k: range(5) for k in list('abcd')})
df.drop(['a', 'c'], axis=1) # Works
df.drop(('a', 'c'), axis=1) # Errors
版本-使用Python2.7.12和Pandas 0.20.3。
最佳答案
元组选择有问题:
np.random.seed(345)
mux = pd.MultiIndex.from_arrays([list('abcde'), list('cdefg')])
df = pd.DataFrame(np.random.randint(10, size=(4,5)), columns=mux)
print (df)
a b c d e
c d e f g
0 8 0 3 9 8
1 4 3 4 1 7
2 4 0 9 6 3
3 8 0 3 1 5
df = df.drop(('a', 'c'), axis=1)
print (df)
b c d e
d e f g
0 0 3 9 8
1 3 4 1 7
2 0 9 6 3
3 0 3 1 5
等同于:
df = df[('a', 'c')]
print (df)
0 8
1 4
2 4
3 8
Name: (a, c), dtype: int32
关于python - Pandas DataFrame删除元组或列列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45736254/