繁体   English   中英

熊猫:在一组中使用多个功能

[英]Pandas: using multiple functions in a group by

我的数据有年龄,也有每月付款。

我正在尝试汇总汇总金额,但没有总结年龄(平均值会有效)。

是否可以为不同的列使用不同的功能?

您可以将字典传递给agg其中列名称作为键,并且您希望将函数作为值。

import pandas as pd
import numpy as np

# Create some randomised data
N = 20
date_range = pd.date_range('01/01/2015', periods=N, freq='W')
df = pd.DataFrame({'ages':np.arange(N), 'payments':np.arange(N)*10}, index=date_range)

print(df.head())
#             ages  payments
# 2015-01-04     0         0
# 2015-01-11     1        10
# 2015-01-18     2        20
# 2015-01-25     3        30
# 2015-02-01     4        40

# Apply np.mean to the ages column and np.sum to the payments.
agg_funcs = {'ages':np.mean, 'payments':np.sum}

# Groupby each individual month and then apply the funcs in agg_funcs
grouped = df.groupby(df.index.to_period('M')).agg(agg_funcs)

print(grouped)
#          ages  payments
# 2015-01   1.5        60
# 2015-02   5.5       220
# 2015-03  10.0       500
# 2015-04  14.5       580
# 2015-05  18.0       540

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM