pandas :在一组中使用多个函数 [英] Pandas: using multiple functions in a group by

查看:108
本文介绍了 pandas :在一组中使用多个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据有年龄限制,还有每月付款。



我正在汇总汇总汇总,但没有总结年龄(平均会起作用)。

对不同的列可以使用不同的函数吗?

解决方案

您可以将字典传递给 agg ,列名作为键和函数你需要作为值。

 将pandas作为pd 
导入numpy作为np

#创建一些随机数据
N = 20
date_range = pd.date_range('01 / 01/2015',句点= N,freq ='W')
df = pd.DataFrame({ 'ages':np.arange(N),'payments':np.arange(N)* 10},index = date_range)

print(df.head())
#年龄支付
#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

#将np.mean应用于年龄栏和np.sum付款。
agg_funcs = {'ages':np.mean,'payments':np.sum}

#Groupby每个月,然后将这些funcs应用于agg_funcs
grouped = df .groupby(df.index.to_period('M'))。agg(agg_funcs)

打印(分组)
#年龄支付
#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


My data has ages, and also payments per month.

I'm trying to aggregate summing the payments, but without summing the ages (averaging would work).

Is it possible to use different functions for different columns?

解决方案

You can pass a dictionary to agg with column names as keys and the functions you want as values.

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

这篇关于 pandas :在一组中使用多个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆