Pandas使用UDF聚合GroupBy对象

时间:2015-10-20 00:18:03

标签: python pandas

假设我有以下内容。我和#34;快乐"然后总结每个小组。它很棒。

import pandas as pd
testdf = pd.DataFrame({"happy": [1, 2, 1, 3], "sad": [4, 5, 6, 7], \
                      "cool":[1, 99, 0, -5]})
testgb = testdf.groupby(["happy"])
testgb.sum()

但是如果我想使用我自己的函数来获取值列表并返回一个数字INSTEAD为sum(),该怎么办?像

def my_max(ilist):
    return max(ilist)
testgb.my_max()

在这种情况下,输出应为:

happy   sad    cool
1       6      1
2       5      99
3       7      -5

有谁知道怎么做?我读了如何使用你自己的函数进行分组而不是累积

1 个答案:

答案 0 :(得分:1)

我假设您要传递其他列的值列表,例如sad。您可以使用agg功能

testdf = pd.DataFrame({"happy": [1, 2, 1, 3], "sad": [4, 5, 6, 7], "cool":[1, 99, 0, -5]})
testgb = testdf.groupby(["happy"]).agg({'sad': lambda x: max(x)})

当然,可能有内置的程序可以实现您的想法但是由于您提出了一个假设的场景,因此很难说更多。

相关问题