【问题标题】:Mutable index? Python Pandas Dataframe ValueError: cannot reindex from a duplicate axis可变索引? Python Pandas Dataframe ValueError:无法从重复的轴重新索引
【发布时间】:2021-06-22 11:54:06
【问题描述】:

我有一个以多个重复值作为索引的数据框,例如:

我需要将 350 包含的值拆分为 351,352,353 等等... 我想更改索引的值以赋予它们唯一值以对其进行唯一操作。我尝试更改索引,但出现此错误:

我的代码的目的是重新索引并仅获取列表中的值。 解决这个问题的最佳方法是什么?有没有办法更改索引值以便我可以处理数据框?

my_finallist = [1,2,3,4,5,6,7]
data_backup.reindex(my_finallist)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-156-2af1a8aae353> in <module>
----> 1 data_backup.reindex(my_finallist)

c:\users\hr085368\appdata\local\programs\python\python39\lib\site-packages\pandas\util\_decorators.py in wrapper(*args, **kwargs)
    310         @wraps(func)
    311         def wrapper(*args, **kwargs) -> Callable[..., Any]:
--> 312             return func(*args, **kwargs)
    313 
    314         kind = inspect.Parameter.POSITIONAL_OR_KEYWORD

c:\users\hr085368\appdata\local\programs\python\python39\lib\site-packages\pandas\core\frame.py in reindex(self, *args, **kwargs)
   4171         kwargs.pop("axis", None)
   4172         kwargs.pop("labels", None)
-> 4173         return super().reindex(**kwargs)
   4174 
   4175     def drop(

c:\users\hr085368\appdata\local\programs\python\python39\lib\site-packages\pandas\core\generic.py in reindex(self, *args, **kwargs)
   4806 
   4807         # perform the reindex on the axes
-> 4808         return self._reindex_axes(
   4809             axes, level, limit, tolerance, method, fill_value, copy
   4810         ).__finalize__(self, method="reindex")

c:\users\hr085368\appdata\local\programs\python\python39\lib\site-packages\pandas\core\frame.py in _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy)
   4017         index = axes["index"]
   4018         if index is not None:
-> 4019             frame = frame._reindex_index(
   4020                 index, method, copy, level, fill_value, limit, tolerance
   4021             )

c:\users\hr085368\appdata\local\programs\python\python39\lib\site-packages\pandas\core\frame.py in _reindex_index(self, new_index, method, copy, level, fill_value, limit, tolerance)
   4036             new_index, method=method, level=level, limit=limit, tolerance=tolerance
   4037         )
-> 4038         return self._reindex_with_indexers(
   4039             {0: [new_index, indexer]},
   4040             copy=copy,

c:\users\hr085368\appdata\local\programs\python\python39\lib\site-packages\pandas\core\generic.py in _reindex_with_indexers(self, reindexers, fill_value, copy, allow_dups)
   4872 
   4873             # TODO: speed up on homogeneous DataFrame objects
-> 4874             new_data = new_data.reindex_indexer(
   4875                 index,
   4876                 indexer,

c:\users\hr085368\appdata\local\programs\python\python39\lib\site-packages\pandas\core\internals\managers.py in reindex_indexer(self, new_axis, indexer, axis, fill_value, allow_dups, copy, consolidate, only_slice)
   1299         # some axes don't allow reindexing with dups
   1300         if not allow_dups:
-> 1301             self.axes[axis]._can_reindex(indexer)
   1302 
   1303         if axis >= self.ndim:

c:\users\hr085368\appdata\local\programs\python\python39\lib\site-packages\pandas\core\indexes\base.py in _can_reindex(self, indexer)
   3474         # trying to reindex on an axis with duplicates
   3475         if not self._index_as_unique and len(indexer):
-> 3476             raise ValueError("cannot reindex from a duplicate axis")
   3477 
   3478     def reindex(self, target, method=None, level=None, limit=None, tolerance=None):

ValueError: cannot reindex from a duplicate axis

【问题讨论】:

  • 那么,索引标签是833还是位置是833?
  • 索引标签为833。我需要将833持有的所有值拆分为834、835、836等...

标签: python python-3.x pandas dataframe


【解决方案1】:

使用rename 也可以很好地处理重复的索引值:

df = df.rename(index={833:778})
#index is default value, so possible use
#df = df.rename({833:778})

如果需要索引值的计数器(但可能会创建新的重复项):

df.index += df.groupby(level=0).cumcount()

#working like
#df.index = df.groupby(level=0).cumcount() + df.index

【讨论】:

  • 我需要将833持有的所有值拆分成834、835、836等...
  • @HariPrasadRangaraj - 嗯,你能解释更多吗?这里的逻辑是什么?在数据集中不是 834, 835, ... 吗?如果使用某些逻辑将833 重命名为834, 835, 836...,则输出不可能重复834835836 以及其他值的相同逻辑?
  • 假设索引 830 包含 5 个值,我需要将所有 5 个值拆分为不同的索引,例如 831,832,833 ,参考我的第一张图片
  • @HariPrasadRangaraj - 那么工作df.index = df.groupby(level=0).cumcount() + df.index ?
  • 那行不通。仍然存在重复...
猜你喜欢
  • 1970-01-01
  • 2020-05-23
  • 2018-02-02
  • 2015-02-26
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多