【问题标题】:How to filter results of a groupby in pandas如何在熊猫中过滤 groupby 的结果
【发布时间】:2014-02-25 08:37:27
【问题描述】:

我正在尝试过滤掉 groupby 的结果。

我有这张桌子:

A       B       C

A0      B0      0.5
A1      B0      0.2
A2      B1      0.6
A3      B1      0.4
A4      B2      1.0
A5      B2      1.2

A是索引,是唯一的。

其次,我有这个清单:

['A0', 'A1', 'A4']

我想按B 分组,并为每个组提取最高值为C 的行。必须在每个组中的所有行之间选择此行,为上面列表中存在索引的行提供最高优先级。

此数据和代码的结果必须是:

A       B       C

A0      B0      0.5
A2      B1      0.6
A4      B2      1.0

我认为的伪代码必须是:

group by B
for each group G:
    intersect group G rows index with indexes in the list
    if intersection is not void:
        the group G becomes the intersection
    sort the rows by C in ascending order
    take the first row as representative for this group

如何在 pandas 中做到这一点?

谢谢

【问题讨论】:

    标签: python filter group-by pandas


    【解决方案1】:

    我是这样解决的:

    # a is the dataframe, s the series
    s = ['A0', 'A1', 'A4']
    
    # take results for the intersection
    results_intersection = a.sort('C', ascending=False).groupby(lambda x: a.ix[x, 'B'] if a.ix[x, 'A'] in s else np.nan).first()
    
    # take remaining results
    missing_results_B = set(a['B'].value_counts().index) - set(results_intersection.index)
    results_addendum = a[a['B'].isin(missing_results_B)].groupby('B').first()
    del results_intersection['B']
    
    # concatenate
    results = pd.concat([results_intersection, results_addendum])
    

    希望它有所帮助,我没有忘记任何事情..

    【讨论】:

      【解决方案2】:

      这是一个通用的解决方案。它不漂亮,但它有效:

      def filtermax(g, filter_on, filter_items, max_over):
          infilter = g.index.isin(filter_items).sum() > 0
          if infilter:
              return g[g[max_over] == g.ix[filter_items][max_over].max()]
          else:
              return g[g[max_over] == g[max_over].max()]
          return g
      

      给出:

      >>> x.groupby('B').apply(filtermax, 'A', ['A0', 'A1', 'A4'], 'C')
              B    C
      B  A          
      B0 A0  B0  0.5
      B1 A2  B1  0.6
      B2 A4  B2  1.0
      

      如果有人能弄清楚如何阻止 B 被添加为索引(至少在我的系统上 x.groupby('B', as_index=False 没有帮助!)那么这个解决方案非常完美!

      【讨论】:

      • 谢谢..我会试试的
      • 如果您喜欢我的回答,请考虑接受。谢谢。
      • @LondonRob 提到的额外索引可以通过:x.groupby('B').apply(filtermax, 'A', ['A0', 'A1', 'A4'], 'C').reset_index(drop=True) 删除。
      猜你喜欢
      • 2018-12-09
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 2016-10-22
      相关资源
      最近更新 更多