【问题标题】:Pandas - How to check if multi index column existsPandas - 如何检查多索引列是否存在
【发布时间】: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] 将导致密钥错误。如何检查是否存在多索引列,以便在处理过程中跳过不存在的列?

谢谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以把多索引想象成一个元组数组,所以可以像这样访问:

    df1[(0, 0.1)]
    

    并像这样测试:

    (0, 0.1) in df1.columns:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 2014-09-12
      • 2011-01-09
      • 2013-11-03
      • 2017-01-01
      • 1970-01-01
      相关资源
      最近更新 更多