gpt4 book ai didi

python - 重新索引错误 - python

转载 作者:行者123 更新时间:2023-12-01 02:11:06 26 4
gpt4 key购买 nike

我的代码有一些问题,有人知道可能出了什么问题

代码

df=df.groupby(by='store')['transaction_number','transaction_amount'].agg(['count','sum']).reset_index()

错误

ValueError: cannot reindex from a duplicate axis

最佳答案

稍微更改一下您的 aggfunc,确保明确告知 agg 它正在聚合哪些列。

c = ['transaction_number','transaction_amount']
f = dict.fromkeys(c, ['count','sum'])

df = df.groupby('store', as_index=False).agg(f)

执行groupby时,您可以指定as_index=False,以便石斑鱼自 Action 为列插入到最终结果中(这比调用更有效>reset_index 在最后)。

<小时/>

这是一个包含一些人为数据的快速演示:

df

store transaction_number transaction_amount
0 a 0 100
1 a 1 200
2 a 2 100
3 b 3 400
4 c 1 50
5 c 3 45

f
{
"transaction_amount": [
"count",
"sum"
],
"transaction_number": [
"count",
"sum"
]
}


df.groupby('store', as_index=False).agg(f)

store transaction_number transaction_amount
count sum count sum
0 a 3 3 3 400
1 b 1 3 1 400
2 c 2 4 2 95

关于python - 重新索引错误 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48694563/

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