gpt4 book ai didi

python - Pandas Dataframe groupby + agg + lambda + unique 抛出 ValueError

转载 作者:行者123 更新时间:2023-12-01 01:22:00 25 4
gpt4 key购买 nike

我有一个类似这样的表,名为 rev_df

       pcid     date        rep     rev    new_rev  diff    Period
0 523468 2017-01-01 1127 16.60 0 NaN 1
1 523468 2017-01-02 1127 41.32 0 1 1
2 523468 2017-01-03 4568 52.39 0 1 1
3 523468 2017-01-04 4568 47.31 0 1 2

这是导致一些 PROBLEMS™ 的相关代码行。

rev_df_period = rev_df.groupby(['pcid', 'Period']).agg({'date': [np.min,np.max], 
'rev':np.sum,
'new_prod_rev':np.sum,
'historical_sales_rep': lambda x: x.unique()
})

lambda x: x.unique() 导致以下错误:

ValueError:函数不减少

通过测试,我发现如果我将最后一个 agg lambda 函数更改为 .nunique(),它不会抛出错误。但我需要唯一rep值的列表,而不是值的数量

有什么想法吗?

输出应如下所示:

                new_rev        date              rev      rep
sum amin amax sum unique
pcid Period
523468 1 0 2017-01-01 2017-02-01 1026.94 [1127,4568]
2 0 2017-03-24 2017-03-30 90.00 4568

最佳答案

你可以试试这个:

df.groupby(['pcid', 'Period']).agg({'date': [np.min,np.max], 
'rev':np.sum,
'new_rev':np.sum,
'rep': lambda x: list(set(x))
})

输出:

                     date                 rev new_rev           rep
amin amax sum sum <lambda>
pcid Period
523468 1 2017-01-01 2017-01-03 110.31 0 [4568, 1127]
2 2017-01-04 2017-01-04 47.31 0 [4568]

编辑以获得正确的列命名

f = lambda x: list(set(x))
f.__name__ = 'unique'

rev_df.groupby(['pcid', 'Period']).agg({'date': [np.min,np.max],
'rev':np.sum,
'new_rev':np.sum,
'rep': f
})

输出:

                     date                 rev new_rev           rep
amin amax sum sum unique
pcid Period
523468 1 2017-01-01 2017-01-03 110.31 0 [4568, 1127]
2 2017-01-04 2017-01-04 47.31 0 [4568]

关于python - Pandas Dataframe groupby + agg + lambda + unique 抛出 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53728876/

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