【问题标题】:Get column value using index dict使用索引dict获取列值
【发布时间】:2018-01-16 15:32:11
【问题描述】:

我有这个熊猫 df:

                      value
index1 index2 index3       
1      1      1        10.0
              2        -0.5
              3         0.0
2      2      1         3.0
              2         0.0
              3         0.0
       3      1         0.0
              2        -5.0
              3         6.0

我想使用 dict 获取特定索引组合的“值”。

通常,我使用,例如:

df = df.iloc[df.index.isin([2],level='index1')]
df = df.iloc[df.index.isin([3],level='index2')]
df = df.iloc[df.index.isin([2],level='index3')]
value = df.values[0][0]

现在,我想使用这本字典以更短的方式获得我的值 = -5:

d = {'index1':2,'index2':3,'index3':2}

而且,如果我使用:

d = {'index1':2,'index2':3}

我想得到数组:

[0.0, -5.0, 6.0]

提示?

【问题讨论】:

    标签: pandas dictionary


    【解决方案1】:

    你可以使用类似SQL的方法DataFrame.query():

    In [69]: df.query(' and '.join('{}=={}'.format(k,v) for k,v in d.items()))
    Out[69]:
                          value
    index1 index2 index3
    2.0    3.0    2        -5.0
    

    对于另一个字典:

    In [77]: d = {'index1':2,'index2':3}
    
    In [78]: df.query(' and '.join('{}=={}'.format(k,v) for k,v in d.items()))
    Out[78]:
                          value
    index1 index2 index3
    2.0    3.0    1         0.0
                  2        -5.0
                  3         6.0
    

    【讨论】:

    • 我是如此接近,但这是非常动态的。
    • 是的,一般的解决方案只有query
    【解决方案2】:

    一种非查询方式是

    In [64]: df.loc[np.logical_and.reduce([
                     df.index.get_level_values(k) == v for k, v in d.items()])]
    Out[64]:
                          value
    index1 index2 index3
    2      3      2        -5.0
    

    【讨论】:

      猜你喜欢
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      相关资源
      最近更新 更多