【发布时间】:2021-06-05 00:00:04
【问题描述】:
鉴于以下数据框,
是否可以计算col2 和col2 + col3 的总和,
在单个聚合函数中?
import pandas as pd
df = pd.DataFrame({'col1': ['a', 'a', 'b', 'b'], 'col2': [1, 2, 3, 4], 'col3': [10, 20, 30, 40]})
| . | col1 | col2 | col3 |
|---|---|---|---|
| 0 | a | 1 | 10 |
| 1 | a | 2 | 20 |
| 2 | b | 3 | 30 |
| 3 | b | 4 | 40 |
在 R 的 dplyr 中,我会使用一行 summarize,
我想知道熊猫中的等价物是什么:
df %>% group_by(col1) %>% summarize(col2_sum = sum(col2), col23_sum = sum(col2 + col3))
期望的结果:
| . | col1 | col2_sum | col23_sum |
|---|---|---|---|
| 0 | a | 3 | 33 |
| 1 | b | 7 | 77 |
【问题讨论】: