gpt4 book ai didi

python - 对多列进行复杂聚合的 Pandas groupby

转载 作者:行者123 更新时间:2023-12-05 05:35:23 26 4
gpt4 key购买 nike

我有以下数据集:

import pandas as pd
from itertools import combinations

d = {'Order_ID': ['001', '001', '002', '003', '003', '003', '004', '004'],
'Products': ['Apple', 'Pear', 'Banana', 'Apple', 'Pear', 'Banana', 'Apple', 'Pear'],
'Revenue': [15, 10, 5, 25, 15, 10, 5, 30]}
df = pd.DataFrame(data=d)
df

产量:

    Order_ID    Products    Revenue
0 001 Apple 15
1 001 Pear 10
2 002 Banana 5
3 003 Apple 25
4 003 Pear 15
5 003 Banana 10
6 004 Apple 5
7 004 Pear 30

我想要实现的是一个数据集,其中包含在所有交易中找到的所有可能的配对组合,获取它们的频率和收入的运行总和。它应该看起来像这样:

d = {'Groups': ['(Apple, Pear)', '(Banana, Apple)', '(Banana, Pear)'], 
'Frequency': [3, 1, 1],
'Revenue': [100, 35, 40]}
df2 = pd.DataFrame(data=d)
df2

哪个返回:

   Groups         Frequency    Revenue
0 (Apple, Pear) 3 100
1 (Banana, Apple) 1 35
2 (Banana, Pear) 1 40

我能够获得配对及其频率,但我无法弄清楚如何在我使用的 groupby 语句中获得收入部分:

def find_pairs(x):
return pd.Series(list(combinations(set(x), 2)))

df_group = df.groupby('Order_ID')['Products'].apply(find_pairs).value_counts()
df_group

我需要在将函数应用于“产品”后添加另一个条件,其中“收入”由 find_pairs 函数创建的这些"new"组相加。收入必须是每对的总和,即每次重复该组时,将产品收入添加到该组的运行总和。

最佳答案

你可以这样做:

f = lambda x: list(itertools.combinations(x,2))
t = df.groupby('Order_ID').agg(f).explode(['Products', 'Revenue']).dropna()
out = t.groupby('Products').agg(
Frequency=('Products','count'),
Revenue=('Revenue', lambda x : sum([sum(y) for y in x]))
)

打印(输出):

                 Frequency  Revenue
Products
(Apple, Banana) 1 35
(Apple, Pear) 3 100
(Pear, Banana) 1 25

请注意,来自组 'Order_ID'='003' 的 (Pear, Banana) 的收入将为 15 + 10 = 25 而不是 40。

关于python - 对多列进行复杂聚合的 Pandas groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73530780/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com