【问题标题】:Pandas: using multiple functions in a group by熊猫:在一个组中使用多个功能
【发布时间】:2015-05-21 13:13:45
【问题描述】:

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

我正在尝试汇总付款的总和,但没有汇总年龄(平均会起作用)。

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

【问题讨论】:

  • 好的,谢谢。 -------------------------------------------------- |日期 |恢复 |年龄 | ---------------------------------------------- |一月 | 500 | 26 | |二月 | 400 | 26 | |三月 | 1000 | 26 |

标签: python pandas group-by aggregate


【解决方案1】:

您可以pass a dictionary to 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-15
    • 2021-05-10
    • 2016-09-21
    • 2018-04-25
    • 2016-03-14
    • 2019-12-19
    • 2018-02-16
    • 2020-04-20
    相关资源
    最近更新 更多