当前位置: 首页 > 知识库问答 >
问题:

无法从重复的轴重新索引

袁法
2023-03-14

我正在处理一个数据管道在空气流,并不断运行到这个值错误:无法重新索引从重复的轴,我已经拍了我的头几天。

这是一个混乱的函数:

def fill_missing_dates(df):
    df['TUNING_EVNT_START_DT'] = pd.to_datetime(df['TUNING_EVNT_START_DT'])
    dates = df.set_index('TUNING_EVNT_START_DT').resample('D').asfreq().index
    masdiv = df['MASDIV'].unique()
    station = df['STATION'].unique()
    idx = pd.MultiIndex.from_product((dates, masdiv, station), names=['TUNING_EVNT_START_DT', 'MASDIV', 'STATION'])
    df = df.set_index(['TUNING_EVNT_START_DT', 'MASDIV', 'STATION']).reindex(idx, fill_value=0).reset_index()

    return df

以下是AWS Cloudwatch日志的错误输出:

16:31:40
dates = df.set_index('TUNING_EVNT_START_DT').resample('D').asfreq().index
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/resample.py", line 821, in asfreq
16:31:40
return self._upsample("asfreq", fill_value=fill_value)
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/resample.py", line 1125, in _upsample
16:31:40
res_index, method=method, limit=limit, fill_value=fill_value
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/util/_decorators.py", line 221, in wrapper
16:31:40
return func(*args, **kwargs)
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/frame.py", line 3976, in reindex
16:31:40
return super().reindex(**kwargs)
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/generic.py", line 4514, in reindex
16:31:40
axes, level, limit, tolerance, method, fill_value, copy
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/frame.py", line 3864, in _reindex_axes
16:31:40
index, method, copy, level, fill_value, limit, tolerance
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/frame.py", line 3886, in _reindex_index
16:31:40
allow_dups=False,
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/generic.py", line 4577, in _reindex_with_indexers
16:31:40
copy=copy,
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/internals/managers.py", line 1251, in reindex_indexer
16:31:40
self.axes[axis]._can_reindex(indexer)
16:31:40
File "/usr/local/lib64/python3.7/site-packages/pandas/core/indexes/base.py", line 3362, in _can_reindex
16:31:40
raise ValueError("cannot reindex from a duplicate axis")
16:31:40
ValueError: cannot reindex from a duplicate axis
16:31:40
"""
16:31:40
The above exception was the direct cause of the following exception:
16:31:40
Traceback (most recent call last):
16:31:40
File "/tmp/scripts/anomaly_detection_model.py", line 275, in <module>
16:31:40
runner(path_prefix, model_name, execution_id, table)
16:31:40
File "/tmp/scripts/anomaly_detection_model.py", line 230, in runner
16:31:40
df = multiprocessing(PROCESSORS, df)
16:31:40
File "/tmp/scripts/anomaly_detection_model.py", line 121, in multiprocessing
16:31:40
x = pool.map(iforest, (df.loc[df['MASDIV'] == masdiv] for masdiv in args))
16:31:40
File "/usr/lib64/python3.7/multiprocessing/pool.py", line 268, in map
16:31:40
return self._map_async(func, iterable, mapstar, chunksize).get()
16:31:40
File "/usr/lib64/python3.7/multiprocessing/pool.py", line 657, in get
16:31:40
raise self._value
16:31:40
ValueError: cannot reindex from a duplicate axis

我已经运行了一些记录器,以了解该步骤中数据帧的输出,但我不知道问题点在哪里:

18:40:34
20/02/07 18:40:34 - INFO - __main__ - Where it breaks: df.index(): RangeIndex(start=0, stop=93, step=1)
18:40:34
20/02/07 18:40:34 - INFO - __main__ - Where it breaks: df.columns: Index(['TUNING_EVNT_START_DT', 'MASDIV', 'STATION', 'DOW', 'MOY',
18:40:34
'TRANSACTIONS', 'DOW_INT', 'MOY_INT', 'DT_NBR'],
18:40:34
dtype='object')

我在这些帖子中尝试了一切,但都没有成功:

错误:无法从重复轴重新索引

ValueError:不能从重复的轴重新索引是什么意思?

我也不完全明白为什么会发生这种情况。任何建议都非常感谢。

共有1个答案

廖鸿达
2023-03-14

没有示例数据,我无法重现您的错误。然而,基于函数名“fill_missing_dates”,我认为这个替代解决方案可能会实现您想要实现的目标。

import pandas as pd

df = pd.DataFrame({
    'date': ["2020-01-01 00:01:00", "2020-01-01 00:02:00", "2020-01-01 01:00:00", "2020-01-01 02:00:00",
             "2020-01-01 00:04:00", "2020-01-01 00:05:00",
             "2020-01-03 00:01:00", "2020-01-03 00:02:00", "2020-01-03 01:00:00", "2020-01-03 02:00:00",
             "2020-01-03 00:04:00", "2020-01-03 00:05:00",
            ],
    'station': ["a","a","a","a","b", "b", "a", "a", "a", "a", "b", "b"],
    'data': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
})

def resampler(x):    
    return x.set_index('date').resample('D').sum()

df['date'] =  pd.to_datetime(df['date'])
multipass = pd.MultiIndex.from_frame(df[["date", "station"]])
df = df.set_index(["date", "station"])
df = df.reindex(multipass)
df.reset_index(level=0).groupby(level=0).apply(resampler)

结果用0填充缺少的日期:

                        data
station  date   
a        2020-01-01     10
         2020-01-02     0
         2020-01-03     34
b        2020-01-01     11
         2020-01-02     0
         2020-01-03     23
 类似资料:
  • 问题内容: 我在尝试将索引设置为某个值时遇到错误。我试图用一个简单的例子重现它,但是我做不到。 这是我跟踪中的会话。我有一个带有字符串索引和整数列,浮点值的DataFrame。但是,当我尝试为所有列的总和创建索引时,出现错误。我创建了一个具有相同特征的小型DataFrame,但无法重现该问题,我可能会丢失什么? 我不太明白这是什么意思,此错误消息是什么意思?也许这可以帮助我诊断问题,这是我问题中最

  • 当我试图将索引设置为某个值时,我得到了一个重新索引。我试图用一个简单的例子来重现这一点,但我做不到。 这是我在跟踪中的会话。我有一个带有字符串索引、整数列和浮点值的数据帧。但是,当我尝试为所有列的总和创建索引时,我得到的错误。我创建了一个具有相同特征的小数据帧,但无法重现问题,我会错过什么? 我真的不明白什么是的意思,这个错误消息是什么意思?也许这会帮助我诊断问题,这是我问题中最值得回答的部分。

  • 我查阅了很多关于ValueError:cannot reindex from a duplicate axis([ValueError:cannot reindex from a duplicate axis'是什么意思?以及其他相关文章。我知道重复的行索引或列名可能会导致错误,但我仍然不能完全弄清楚到底是什么原因导致了我出现错误。 下面是我最擅长重现数据框架的精神,它确实会抛出错误。 以下是错误

  • 本文向大家介绍python 重命名轴索引的方法,包括了python 重命名轴索引的方法的使用技巧和注意事项,需要的朋友参考一下 如下所示: 以上这篇python 重命名轴索引的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

  • 问题内容: 这个问题已经在这里有了答案 : While循环中的ReactorNotRestartable错误出现刮擦 (7个答案) 去年关闭。 与: 我一直成功地运行了此过程: 但由于我已将此代码移入一个函数中,因此: 并开始使用类实例化调用该方法,例如: 并运行: 我收到以下错误: 怎么了? 问题答案: 您不能重新启动反应堆,但是应该可以通过分叉一个单独的过程来使其运行更多次: 运行两次: 结果

  • 我有一个数据框 我只想保留唯一的索引,因为索引1是重复的,我想删除它的第二个实例,我该怎么做?我想要我的结果