簡體   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