【问题标题】:How to include a condition with a multiindex filter in pandas?如何在熊猫中包含带有多索引过滤器的条件?
【发布时间】:2019-11-14 01:33:26
【问题描述】:

我有一个由多索引组成的过滤器。我想仅对该多索引中包含的值应用条件。有可能吗?

arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

# this multiindex comes from a model so it is fixed and we cannot know the values in advance
fixed_multiindex = pd.MultiIndex.from_tuples([('bar','one'), ('foo', 'one')])

df_multinidex_and_condition = df.loc[(fixed_multiindex) & (df[0] > -1.3)]

错误

Output error TypeError: other must be a MultiIndex or a list of tuples

【问题讨论】:

    标签: python pandas multi-index


    【解决方案1】:

    使用Index.isin:

    df_multinidex_and_condition = df.loc[df.index.isin(fixed_multiindex) & (df[0] > -1.3)]
    print (df_multinidex_and_condition)
                    0         1         2         3
    bar one -0.217679  0.821455  1.481278  1.331864
    foo one  2.672172  0.464802  0.845930 -0.503542
    

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 2017-06-03
      • 2020-04-19
      • 2021-08-28
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 2018-08-09
      相关资源
      最近更新 更多