【问题标题】:resample irregularly spaced data in pandas在熊猫中重新采样不规则间隔的数据
【发布时间】:2017-04-27 23:34:12
【问题描述】:

是否可以在不规则间隔的数据上使用resample? (我知道文档说它是用于“对常规时间序列数据进行重新采样”,但我想尝试它是否也适用于不规则数据。也许它没有,或者我做错了什么。)

在我的真实数据中,我通常每小时有 2 个样本,它们之间的时间差通常在 20 到 40 分钟之间。所以我希望将它们重新采样为定期的每小时系列。

为了测试我是否正确使用它,我使用了一些我已经拥有的随机日期列表,因此它可能不是一个最佳示例,但至少适用于它的解决方案将非常强大。在这里:

    fraction  number                time
0   0.729797       0 2014-10-23 15:44:00
1   0.141084       1 2014-10-30 19:10:00
2   0.226900       2 2014-11-05 21:30:00
3   0.960937       3 2014-11-07 05:50:00
4   0.452835       4 2014-11-12 12:20:00
5   0.578495       5 2014-11-13 13:57:00
6   0.352142       6 2014-11-15 05:00:00
7   0.104814       7 2014-11-18 07:50:00
8   0.345633       8 2014-11-19 13:37:00
9   0.498004       9 2014-11-19 22:47:00
10  0.131665      10 2014-11-24 15:28:00
11  0.654018      11 2014-11-26 10:00:00
12  0.886092      12 2014-12-04 06:37:00
13  0.839767      13 2014-12-09 00:50:00
14  0.257997      14 2014-12-09 02:00:00
15  0.526350      15 2014-12-09 02:33:00

现在我想重新采样这些,例如每月:

df_new = df.set_index(pd.DatetimeIndex(df['time']))
df_new['fraction'] = df.fraction.resample('M',how='mean')
df_new['number'] = df.number.resample('M',how='mean')

但是我得到TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex' - 除非我在分配日期时间索引时做错了什么,否则一定是由于不规则?

所以我的问题是:

  1. 我是否正确使用它?
  2. 如果 1==True,是否没有直接的方法来重新采样数据?

(我只看到一个解决方案,首先重新索引数据以获得更精细的间隔,在其间插入值,然后将其重新索引为每小时间隔。如果是这样,那么关于重新索引的正确实施的问题将很快出现。 )

【问题讨论】:

  • 熊猫版本 0.18.1,python 2.7

标签: python pandas


【解决方案1】:

您不需要显式使用DatetimeIndex,只需将'time' 设置为索引,pandas 会处理其余部分,只要您的'time' 列已使用pd.to_datetime 或其他一些方法。此外,如果您使用相同的方法,则无需单独重新采样每一列;只需在整个 DataFrame 上执行即可。

# Convert to datetime, if necessary.
df['time'] = pd.to_datetime(df['time'])

# Set the index and resample (using month start freq for compact output).
df = df.set_index('time')
df = df.resample('MS').mean()

结果输出:

            fraction  number
time                        
2014-10-01  0.435441     0.5
2014-11-01  0.430544     6.5
2014-12-01  0.627552    13.5

【讨论】:

猜你喜欢
  • 2011-04-21
  • 2013-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2022-06-10
  • 2019-10-09
  • 2020-01-10
  • 2021-03-11
相关资源
最近更新 更多