【问题标题】:How to filter pandas dataframe with unique ID and perform calculation on other column? [duplicate]如何过滤具有唯一 ID 的 pandas 数据框并在其他列上执行计算? [复制]
【发布时间】:2019-05-11 23:26:00
【问题描述】:

我有一个如下所示的数据框。我想过滤我的数据框,使数据框显示唯一的类型:A、B、C、D。但是,我也想对这些值求和。对于 A 类,它将是 8+15=13

当前数据框:

ID  type value
1   A    8
2   A    5
3   B    11
4   C    12
5   D    1
6   D    22
7   D    13

预期输出

ID  type value
1   A    13
3   B    11
4   C    12
5   D    36

我是 python 的新手。非常感谢带有解释的代码!

【问题讨论】:

  • df.groupby('type').value.sum()

标签: python pandas aggregation


【解决方案1】:

使用groupby:

print(df.groupby('type',as_index=False)['value'].sum())

如需'ID'栏目:

print(df.groupby('type',as_index=False).agg({'ID':'first','value':'sum'}))

【讨论】:

  • 感谢您的努力!我想保持我的身份证号码不变。我怎样才能做到这一点?
  • @biggboss2019 我会编辑,如果可行,记得接受 :-)
  • @biggboss2019 编辑了我的。记得也要投票:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2020-11-15
  • 2022-10-30
  • 1970-01-01
相关资源
最近更新 更多