[英]GroupBy aggregate function that computes two values at once
我有一個如下的數據名:
import pandas as pd
df = pd.DataFrame({
'A': [1, 1, 1, 2, 2, 2],
'B': [1, 2, 3, 4, 5, 6],
'C': [4, 5, 6, 7, 8, 9],
})
現在我想對每組產生兩個值進行分組和聚合。 結果應類似於以下內容:
expected = df.groupby('A').agg([min, max])
# B C
# min max min max
# A
# 1 1 3 4 6
# 2 4 6 7 9
但是,在我的例子中,我有一個 function 來一次計算這兩個值,而不是兩個不同的函數min
和max
:
def minmax(x):
"""This function promises to compute the min and max in one go."""
return min(x), max(x)
現在我的問題是,如何使用這個function為每組生成兩個聚合值?
這有點與這個答案有關,但我不知道該怎么做。 我能想到的最好的方法是使用雙重嵌套apply
,但這不是很優雅,而且它會在行而不是列上產生多索引:
result = df.groupby('A').apply(
lambda g: g.drop(columns='A').apply(
lambda h: pd.Series(dict(zip(['min', 'max'], minmax(h))))
)
)
# B C
# A
# 1 min 1 4
# max 3 6
# 2 min 4 7
# max 6 9
如果您遇到返回值tuple
的 function 。 ID:
tuple
值包裝到一個dict
中,以便您預定義dict.keys()
以與您想要的列名對齊。for
循環。# Given Function
def minmax(x):
"""This function promises to compute the min and max in one go."""
return min(x), max(x)
# wrapped function
def minmax_dict(x):
return dict(zip(['min', 'max'], minmax(x)))
for
循環我的目標是將此字典傳遞給pd.DataFrame
構造函數。 這意味着,我想要鍵中的MultiIndex
列元素的元組。 我希望這些值是字典,鍵是索引元素。
dat = {}
for a, d in df.set_index('A').groupby('A'):
for cn, c in d.iteritems():
for k, v in minmax_dict(c).items():
dat.setdefault((cn, k), {})[a] = v
pd.DataFrame(dat).rename_axis('A')
B C
min max min max
A
1 1 3 4 6
2 4 6 7 9
看看精心制作的字典
data
{('B', 'min'): {1: 1, 2: 4},
('B', 'max'): {1: 3, 2: 6},
('C', 'min'): {1: 4, 2: 7},
('C', 'max'): {1: 6, 2: 9}}
另一種解決方案:
pd.concat({k:d.agg(minmax).set_axis(['min','max'])
for k,d in df.drop('A',axis=1).groupby(df['A'])
})
Output:
B C
1 min 1 4
max 3 6
2 min 4 7
max 6 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.