ValueError:无法使用 groupy 从重复轴重新索引并在 Pandas 中应用 pct_change

Posted

技术标签:

【中文标题】ValueError:无法使用 groupy 从重复轴重新索引并在 Pandas 中应用 pct_change【英文标题】:ValueError: cannot reindex from a duplicate axis using groupy and apply pct_change in Pandas 【发布时间】:2020-04-06 13:11:36 【问题描述】:

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

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

【问题讨论】:

您的索引中很可能有重复值。检查此链接***.com/questions/27236275/… 【参考方案1】:

如果我的索引中有重复项,我会收到同样的错误。你需要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

【讨论】:

我尝试使用我的真实数据,代码有效,但结果似乎不正确。 ;(

以上是关于ValueError:无法使用 groupy 从重复轴重新索引并在 Pandas 中应用 pct_change的主要内容,如果未能解决你的问题,请参考以下文章

致命:无法从重定向更新 url 库

ValueError("无法使用 `eval()` 评估张量:

使用 NSURLSessionDownloadTask 从重定向 URL 下载 pdf 文件

ValueError:使用带有 seaborn 线图的索引时无法解释输入“索引”

无法使用新观察值更新 StatsModels SARIMAX (ValueError)

ValueError:无法使用 dtype='numeric' 将字节/字符串数组转换为十进制数