groupby 自定义聚合操作
时间: 2023-07-28 18:09:56 浏览: 45
在 Pandas 中,我们可以使用 `groupby` 方法按照某个列或多个列进行分组,然后对每个分组进行聚合操作。Pandas 提供了很多内置的聚合函数,如 `sum`、`mean`、`count` 等等。除此之外,我们也可以自定义聚合函数来满足我们的需求。下面是一个例子:
假设我们有一份包含用户消费记录的数据集,其中包含用户 ID、消费日期和消费金额。我们希望按照用户 ID 进行分组,并计算每个用户的总消费金额和平均消费金额。
首先,我们可以使用 `groupby` 方法按照用户 ID 进行分组:
```
import pandas as pd
data = {
'user_id': ['A', 'A', 'B', 'B', 'C'],
'date': ['2021-01-01', '2021-02-01', '2021-01-01', '2021-02-01', '2021-01-01'],
'amount': [100, 200, 150, 250, 300]
}
df = pd.DataFrame(data)
grouped = df.groupby('user_id')
```
然后,我们可以定义一个自定义聚合函数,来计算每个用户的总消费金额和平均消费金额:
```
def custom_agg(x):
total_amount = x['amount'].sum()
avg_amount = x['amount'].mean()
return pd.Series({'total_amount': total_amount, 'avg_amount': avg_amount})
```
最后,我们可以使用 `agg` 方法,将自定义聚合函数应用到每个分组上:
```
result = grouped.agg(custom_agg)
```
`result` 的结果如下:
```
total_amount avg_amount
user_id
A 300 150.0
B 400 200.0
C 300 300.0
```
其中,`total_amount` 列表示每个用户的总消费金额,`avg_amount` 列表示每个用户的平均消费金额。