python - 值错误 : cannot reindex from a duplicate axis when assigning new column to pandas DataFrame

标签 python python-3.x pandas dataframe

我试图弄清楚我的日期时间索引中有哪些时间介于 2 个不同的时间之间。

这是我的代码:

rbe60['result'] = rbe60.index.hour.to_series().between(3,23)

唯一的问题是我一直收到这个错误。

    raise ValueError("cannot reindex from a duplicate axis")
ValueError: cannot reindex from a duplicate axis

我查看了其他一些帖子并意识到这意味着我的索引或列中的某处可能有重复值。我试着跑去看看重复项在哪里,但结果都是空的。

dup = rbe60.index.get_duplicates() and 
dup = rbe60.columns.get_duplicates()

还有什么我应该尝试的吗?

更多关于我正在尝试做的事情:

这是我的数据,我只是想向 np.logical 语句添加一个条件,该语句检查我的数据帧索引的小时数是否在 3 到 23 之间。

                       Open       H       L       C       O
DateTime                                                   
2013-12-30 14:30:00 -0.0756 -0.0729 -0.0756 -0.0737  2.8847
2013-12-30 15:30:00 -0.0735  -0.072 -0.0737 -0.0722  2.8870
2013-12-30 16:30:00 -0.0722 -0.0721 -0.0728 -0.0722  2.8930
2013-12-30 18:00:00 -0.0728 -0.0728 -0.0728 -0.0728  2.8826
2013-12-30 19:00:00 -0.0721 -0.0721 -0.0721 -0.0721  2.8872

最佳答案

错误的原因是索引对齐。您的 DataFrame 由 datetime 的索引组成。您现有的代码返回如下内容:

print(rbe60.index.hour.to_series().between(3,23))
DateTime
14    True
15    True
16    True
18    True
19    True
Name: DateTime, dtype: bool

请注意索引值与原始索引值不匹配。这会在分配期间抛出 Pandas 。解决方案是分配一个根本不与索引关联的数组。

print(rbe60.index.hour.to_series().between(3,23).values)
array([ True,  True,  True,  True,  True])

现在,

rbe60['result'] = rbe60.index.hour.to_series().between(3,23).values

关于python - 值错误 : cannot reindex from a duplicate axis when assigning new column to pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53622190/

相关文章:

python - 在退出 Python 程序之前等待所有守护线程完成的简单方法?

python - 是什么导致 ImportError : No module named pkg_resources after upgrade of Python on os X?

python - 计算列表内重复列表的数量

python - Nautilus 右键单击​​菜单中的子菜单项

python - 减少 Python 中 xgboost 增量训练的错误率

python - 在类上覆盖 dict()

python - 如何更新 Celery Task ETA?

python - 重命名未堆叠数据透视表中的 pandas 列值

python - 如何检查字符串中是否包含某个单词?

python - 将 cx_Oracle arraysize 参数与 pandas read_sql 结合使用