python - `ValueError: cannot reindex from a duplic

当我尝试将索引设置为某个值时,我收到 ValueError: cannot reindex from a duplicate axis。我试图用一个简单的例子重现这一点,但我做不到。

这是我在 ipdb 跟踪中的 session 。我有一个带有字符串索引、整数列、浮点值的 DataFrame。但是,当我尝试为所有列的总和创建 sum 索引时,我得到 ValueError: cannot reindex from a duplicate axis 错误。我创建了一个具有相同特征的小型 DataFrame,但无法重现问题,我可能缺少什么?

我不太明白 ValueError: cannot reindex from a duplicate axis 是什么意思,这个错误信息是什么意思?也许这将帮助我诊断问题,这是我问题中最容易回答的部分。

ipdb> type(affinity_matrix)
<class 'pandas.core.frame.DataFrame'>
ipdb> affinity_matrix.shape
(333, 10)
ipdb> affinity_matrix.columns
Int64Index([9315684, 9315597, 9316591, 9320520, 9321163, 9320615, 9321187, 9319487, 9319467, 9320484], dtype='int64')
ipdb> affinity_matrix.index
Index([u'001', u'002', u'003', u'004', u'005', u'008', u'009', u'010', u'011', u'014', u'015', u'016', u'018', u'020', u'021', u'022', u'024', u'025', u'026', u'027', u'028', u'029', u'030', u'032', u'033', u'034', u'035', u'036', u'039', u'040', u'041', u'042', u'043', u'044', u'045', u'047', u'047', u'048', u'050', u'053', u'054', u'055', u'056', u'057', u'058', u'059', u'060', u'061', u'062', u'063', u'065', u'067', u'068', u'069', u'070', u'071', u'072', u'073', u'074', u'075', u'076', u'077', u'078', u'080', u'082', u'083', u'084', u'085', u'086', u'089', u'090', u'091', u'092', u'093', u'094', u'095', u'096', u'097', u'098', u'100', u'101', u'103', u'104', u'105', u'106', u'107', u'108', u'109', u'110', u'111', u'112', u'113', u'114', u'115', u'116', u'117', u'118', u'119', u'121', u'122', ...], dtype='object')

ipdb> affinity_matrix.values.dtype
dtype('float64')
ipdb> 'sums' in affinity_matrix.index
False

这是错误:

ipdb> affinity_matrix.loc['sums'] = affinity_matrix.sum(axis=0)
*** ValueError: cannot reindex from a duplicate axis

我试图用一个简单的例子来重现这个,但我失败了

In [32]: import pandas as pd

In [33]: import numpy as np

In [34]: a = np.arange(35).reshape(5,7)

In [35]: df = pd.DataFrame(a, ['x', 'y', 'u', 'z', 'w'], range(10, 17))

In [36]: df.values.dtype
Out[36]: dtype('int64')

In [37]: df.loc['sums'] = df.sum(axis=0)

In [38]: df
Out[38]: 
      10  11  12  13  14  15   16
x      0   1   2   3   4   5    6
y      7   8   9  10  11  12   13
u     14  15  16  17  18  19   20
z     21  22  23  24  25  26   27
w     28  29  30  31  32  33   34
sums  70  75  80  85  90  95  100

最佳答案

当您在索引具有重复值时加入/分配给列时,通常会出现此错误。由于您正在分配一行,我怀疑 affinity_matrix.columns 中存在重复值,可能未在您的问题中显示。

关于python - `ValueError: cannot reindex from a duplicate axis` 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27236275/

相关文章:

python - 使用 Python 向 RESTful API 发出请求

python - 如何从 python 代码调用 shell 脚本?

linux - 如何在 Linux 上获得整体 CPU 使用率(例如 57%)

python - 如何在不明确列出列的情况下从 pandas DataFrame 中选择具有一个或多

linux - 如何永久清除 linux/ubuntu 终端或 bash 中的所有历史记录?

linux - 如何在bash中创建仅包含十六进制字符而不包含空格的文件的十六进制转储?

linux - sh : 0: getcwd() failed: No such file or d

linux - 确定 yum 软件包安装到的路径

python - 如何使用 python/numpy 计算百分位数?

python - 如何在 Django 中的 CharField 上添加占位符?