python - Pandas unstack 问题 : ValueError: Index contains duplicate entries, 无法 reshape

标签 python pandas

我正在尝试使用 pandas 取消堆叠多索引,但我不断收到:

ValueError: Index contains duplicate entries, cannot reshape

给定一个有四列的数据集:

  • id(字符串)
  • 日期(字符串)
  • 位置(字符串)
  • 值( float )

我先设置了一个三级多索引:

In [37]: e.set_index(['id', 'date', 'location'], inplace=True)

In [38]: e
Out[38]: 
                                    value
id           date       location       
id1          2014-12-12 loc1        16.86
             2014-12-11 loc1        17.18
             2014-12-10 loc1        17.03
             2014-12-09 loc1        17.28

然后我尝试取消堆叠位置:

In [39]: e.unstack('location')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-39-bc1e237a0ed7> in <module>()
----> 1 e.unstack('location')
...
C:\Anaconda\envs\sandbox\lib\site-packages\pandas\core\reshape.pyc in _make_selectors(self)
    143 
    144         if mask.sum() < len(self.index):
--> 145             raise ValueError('Index contains duplicate entries, '
    146                              'cannot reshape')
    147 

ValueError: Index contains duplicate entries, cannot reshape

这是怎么回事?

最佳答案

这是一个显示这一点的示例 DataFrame,它具有相同索引的重复值。问题是,您是要汇总这些还是将它们保留为多行?

In [11]: df
Out[11]:
   0  1  2      3
0  1  2  a  16.86
1  1  2  a  17.18
2  1  4  a  17.03
3  2  5  b  17.28

In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')  # desired?
Out[12]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

In [13]: df1 = df.set_index([0, 1, 2])

In [14]: df1
Out[14]:
           3
0 1 2
1 2 a  16.86
    a  17.18
  4 a  17.03
2 5 b  17.28

In [15]: df1.unstack(2)
ValueError: Index contains duplicate entries, cannot reshape

一种解决方案是reset_index(并返回到df)并使用pivot_table

In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')
Out[16]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

另一种选择(如果您不想聚合)是附加一个虚拟关卡,将其取消堆叠,然后删除该虚拟关卡...

关于python - Pandas unstack 问题 : ValueError: Index contains duplicate entries, 无法 reshape ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28651079/

相关文章:

Python ctypes : Python file object <-> C FILE *

python - 删除前导和尾随斜杠/在python中

python - 按时间点拆分多个对象的 csv 文件

pandas - Seaborn:如何在绘图 X 轴中的每个值后面添加 "%"符号,而不是将值转换为百分比?

python - 如何使用 pandas 获取数据框中具有特定值的列数?

python - pow 运算符的计算错误

python - tf.keras.metrics.SpecificityAtSensitivity num_thresholds 解释

python - Pandas - 迭代时重复行

python - 基于列值的 Pandas 重新索引任务

python - 重采样错误 : ValueError: month must be in 1. .12