【问题标题】:Pandas conditional group by and sumPandas 条件分组和求和
【发布时间】:2018-07-30 22:41:50
【问题描述】:

有没有一种方法可以对 DataFrame 的某些行进行 groupby 和 sum,但其余部分保持原样?例如我有 df:

df = pd.DataFrame({
'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})

看起来像:

     A      B         C         D
0  foo    one  0.469112 -0.861849
1  bar    one -0.282863 -2.104569
2  foo    two -1.509059 -0.494929
3  bar  three -1.135632  1.071804
4  foo    two  1.212112  0.721555
5  bar    two -0.173215 -0.706771
6  foo    one  0.119209 -1.039575
7  foo  three -1.044236  0.271860

现在我想对B 中的值为one 的行进行分组/求和(并将最后一次出现在A 列中)。所以输出将是:

     A      B      sumC      sumD
1  foo    two -1.509059 -0.494929
2  bar  three -1.135632  1.071804
3  foo    two  1.212112  0.721555
4  bar    two -0.173215 -0.706771
5  foo    one  0.030545 -4.005993
6  foo  three -1.044236  0.271860

如何做到这一点?

【问题讨论】:

  • 我有点糊涂,所以最后一组one的位置不重要吗?您可以通过接受的答案更改预期输出吗?
  • 不,这不重要。如果我愿意,我可以对行进行排序。接受的答案完美无缺,我不介意最后一组 one 在哪里,只要求和即可。
  • 好的,谢谢您的解释。所以我的答案将被删除。

标签: python pandas group-by sum


【解决方案1】:

让我们使用这个:

pd.concat([df.query('B != "one"'),
           df.query('B == "one"').groupby('B', as_index=False)['A','C','D']
             .agg({'A':'last','C':'sum','D':'sum'})])

输出:

     A      B         C         D
2  foo    two  0.656942 -0.605847
3  bar  three  1.022090  0.493374
4  foo    two -1.016595  0.652162
5  bar    two -0.738758 -0.669947
7  foo  three  0.913342  1.156044
0  foo    one  0.590764 -0.192638

【讨论】:

    【解决方案2】:

    另一种解决方法是定义一个新列,如果Bone,则该列是常量(例如-1),否则定义一个唯一值(例如范围),然后对其进行分组。

    df['B2'] = np.where(df['B']=='one', -1, np.arange(len(df)))
    df.groupby('B2', as_index=False).agg({'A': 'last', 'B': 'max', 'C': 'sum', 'D': 'sum'}).drop('B2', axis=1)
    

    这避免了你最终丢弃的计算(尽管,如果你真的想避免这些事情,可能最简单的事情就是将你的 DataFrame 分成两部分,df.B == 'one'df.B != 'one',工作仅在前者上,然后将结果连接回来)

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2016-07-09
      相关资源
      最近更新 更多