【问题标题】:Conditions on mutli-index + data多索引+数据的条件
【发布时间】:2018-11-22 16:00:54
【问题描述】:

我有以下数据框,我正在分组以获得多索引数据框:

    In[33]: df = pd.DataFrame([[0, 'foo', 5], [0, 'foo', 7], [1, 'foo', 4], [1, 'bar', 5], [1, 'foo', 6], [1, 'bar', 2], [2, 'bar', 3]], columns=['id', 'foobar', 'A'])
In[34]: df
Out[34]: 
   id foobar  A
0   0    foo  5
1   0    foo  7
2   1    foo  4
3   1    bar  5
4   1    foo  6
5   1    bar  2
6   2    bar  3
In[35]: df.groupby(['id', 'foobar']).size()
Out[35]: 
id  foobar
0   foo       2
1   bar       2
    foo       2
2   bar       1
dtype: int64

我想在 "id" 中获取 "foo" 的数量 >= 2 和 "bar" 的数量 >= 2 的行,所以基本上得到:

   foobar  A
id          
1     bar  2
      foo  2

但是我有点迷茫,我应该如何用多索引来陈述这个条件?

编辑:这与How to filter dates on multiindex dataframe 无关,因为我不使用日期,并且我需要数据框中特定值数量的条件。

【问题讨论】:

标签: python pandas


【解决方案1】:

unstack之后使用all,然后选择你需要的,stack返回

new=df.groupby(['id', 'foobar']).size().unstack(fill_value=0)
new[new.ge(2).all(1)].stack()
id  foobar
1   bar       2
    foo       2
dtype: int64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2020-09-13
    • 2017-06-10
    • 2020-05-03
    相关资源
    最近更新 更多