【发布时间】:2016-09-19 16:50:41
【问题描述】:
我的问题类似于How to check if a column exists in Pandas,但针对多索引列的情况。
我正在尝试使用源自另一个文件的列名来处理多索引列数据框中的值 - 因此需要检查该列是否存在。一个有代表性的例子如下:
import pandas as pd
from numpy.random import randint,randn
df = pd.DataFrame({ 'A': [randint(0,3) for p in range(0,12)],'B': [0.1* randint(0,3) for p in range(0,12)],
'C': [0.1*randint(0,3) for p in range(0,12)],'D': randn(12),
})
df1 = df.groupby(['A','B','C']).D.sum().unstack(-1)
df1 = df1.T
df1
A 0 1 2
B 0.0 0.2 0.0 0.1 0.2 0.0 0.1
C
0.0 NaN NaN NaN 0.845316 NaN 0.555513 NaN
0.1 NaN 0.139371 NaN NaN NaN NaN -0.260868
0.2 5.002509 NaN 0.637353 0.438863 0.943098 NaN NaN
df1[1][0.1]
C
0.0 0.845316
0.1 NaN
0.2 0.438863
在上述示例中访问df1[0][0.1] 将导致密钥错误。如何检查是否存在多索引列,以便在处理过程中跳过不存在的列?
谢谢!
【问题讨论】: