【问题标题】:Resample error: ValueError: cannot reindex a non-unique index with a method or limit重采样错误:ValueError:无法使用方法或限制重新索引非唯一索引
【发布时间】:2020-05-01 20:55:27
【问题描述】:

我的数据框如下所示:

    timestamp
2020-03-01 01:11:42.520      -674.0
2020-03-01 02:00:48.778      -700.0
2020-03-01 02:00:58.850      -702.0
2020-03-01 11:45:23.741     -1249.0
2020-03-02 01:56:51.021     -1229.0
2020-03-02 01:56:51.021      -917.0
2020-03-02 01:56:51.021      -837.0

我尝试做的是:

cum = (orders[['cum']]
        .resample('1S')
        .bfill()
        .fillna('ffill')
      )

然后我收到标题错误消息,知道它是什么意思吗?感谢您的帮助!

【问题讨论】:

  • 时间戳列有重复项。尝试创建一个传统的索引列。

标签: python pandas


【解决方案1】:

一个想法是首先过滤重复的索引值以像您的解决方案一样重新采样,然后过滤重复到 added 系列,按楼层更改索引并通过排序添加到原始值:

print (orders)
                            cum
timestamp                      
2020-03-01 01:11:42.520  -674.0
2020-03-01 02:00:48.778  -700.0
2020-03-01 02:00:58.850  -702.0
2020-03-01 11:45:23.741 -1249.0
2020-03-02 01:56:51.021 -1229.0
2020-03-02 01:56:51.021  -917.0
2020-03-02 01:56:51.021  -837.0
2020-03-02 01:56:54.021   -67.0

mask = orders.index.duplicated()
cum = (orders.loc[~mask, 'cum']
        .resample('1S')
        .bfill()
        .ffill()
      )
added = orders.loc[mask, 'cum']
added.index = added.index.floor('S')
cum = added.append(cum).sort_index()
print (cum.tail(10))
timestamp
2020-03-02 01:56:47   -1229.0
2020-03-02 01:56:48   -1229.0
2020-03-02 01:56:49   -1229.0
2020-03-02 01:56:50   -1229.0
2020-03-02 01:56:51   -1229.0
2020-03-02 01:56:51    -917.0
2020-03-02 01:56:51    -837.0
2020-03-02 01:56:52     -67.0
2020-03-02 01:56:53     -67.0
2020-03-02 01:56:54     -67.0
Name: cum, dtype: float64

【讨论】:

  • @Viktor.w - 经过测试,需要将 mask = orders.index.duplicated() 更改为 mask = orders.index.duplicated(keep='last')
猜你喜欢
  • 2017-02-09
  • 2017-12-06
  • 1970-01-01
  • 2021-03-05
  • 2015-02-26
  • 1970-01-01
  • 2016-05-17
  • 2020-05-23
  • 2018-02-02
相关资源
最近更新 更多