gpt4 book ai didi

python - 值错误: cannot reindex from a duplicate axis using groupy and apply pct_change in Pandas

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

我尝试计算groupby pct_change使用df.groupby('type')['value'].apply(lambda x: x.pct_change())对于数据框。

但它会生成ValueError: cannot reindex from a duplicate axis ,有什么想法如何处理这个问题吗?谢谢。

最佳答案

如果我的索引中有重复项,我会收到同样的错误。您需要reset_index():

In [726]: df.append(df)                                                                                                                                                                        
Out[726]:
customer brand product quantity price new_quantity
0 C1 B1 P1 100 5 500
1 C1 B1 P2 10 20 200
2 C1 B2 P3 50 7 350
3 C2 B1 P1 75 5 375
4 C2 B2 P3 5 7 35
0 C1 B1 P1 100 5 500
1 C1 B1 P2 10 20 200
2 C1 B2 P3 50 7 350
3 C2 B1 P1 75 5 375
4 C2 B2 P3 5 7 35

df.groupby('customer')['quantity'].apply(lambda x: x.pct_change())

# ValueError: cannot reindex from a duplicate axis

In [730]: df.append(df).reset_index().groupby('customer')['quantity'].apply(lambda x: x.pct_change())                                                                                          
Out[730]:
0 NaN
1 -0.900000
2 4.000000
3 NaN
4 -0.933333
5 1.000000
6 -0.900000
7 4.000000
8 14.000000
9 -0.933333
Name: quantity, dtype: float64

关于python - 值错误: cannot reindex from a duplicate axis using groupy and apply pct_change in Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59316527/

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