我正在尝试用 pandas 解开多索引,并且不断收到:
ValueError: Index contains duplicate entries, cannot reshape
给定一个包含四列的数据集:
- id(字符串)
- 日期(字符串)
- 位置(字符串)
- 值(浮点数)
我首先设置了三级多索引:
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
另一种选择(如果您不想聚合)是附加一个虚拟级别,将其取消堆叠,然后删除虚拟级别...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)