使用 pandas 对 python 列表重新采样

Resample python list with pandas

对这里的 python 和 pandas 相当陌生。

我查询返回了一个时间序列。我永远不确定我从查询中收到了多少数据点(运行 一天),但我所知道的是我需要对它们重新采样以包含 24 个点(一天中每小时一个) ).

打印 m3hstream 得到

[(1479218009000L, 109), (1479287368000L, 84)]

然后我尝试用

制作一个数据帧 df
df = pd.DataFrame(data = list(m3hstream), columns=['Timestamp', 'Value'])

这给了我

的输出
          Timestamp  Value
       0  1479218009000    109
       1  1479287368000     84

下面我这样做

 daily_summary = pd.DataFrame()
 daily_summary['value'] = df['Value'].resample('H').mean()
 daily_summary = daily_summary.truncate(before=start, after=end)
 print "Now daily summary"
 print daily_summary

但这给了我一个 TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'

任何人都可以告诉我如何对其重新采样,以便我在查询的 24 小时内每小时获得 1 分吗?

谢谢。

让我们试试:

daily_summary = daily_summary.set_index('Timestamp')

daily_summary.index = pd.to_datetime(daily_summary.index, unit='ms')

每小时一次:

daily_summary.resample('H').mean()

或每天一次:

daily_summary.resample('D').mean()
  • 您需要做的第一件事是将 'Timestamp' 转换为实际的 pd.Timestamp。看起来这些是 milliseconds
  • 然后 resampleon 参数设置为 'Timestamp'

df = df.assign(
    Timestamp=pd.to_datetime(df.Timestamp, unit='ms')
).resample('H', on='Timestamp').mean().reset_index()

             Timestamp  Value
0  2016-11-15 13:00:00  109.0
1  2016-11-15 14:00:00    NaN
2  2016-11-15 15:00:00    NaN
3  2016-11-15 16:00:00    NaN
4  2016-11-15 17:00:00    NaN
5  2016-11-15 18:00:00    NaN
6  2016-11-15 19:00:00    NaN
7  2016-11-15 20:00:00    NaN
8  2016-11-15 21:00:00    NaN
9  2016-11-15 22:00:00    NaN
10 2016-11-15 23:00:00    NaN
11 2016-11-16 00:00:00    NaN
12 2016-11-16 01:00:00    NaN
13 2016-11-16 02:00:00    NaN
14 2016-11-16 03:00:00    NaN
15 2016-11-16 04:00:00    NaN
16 2016-11-16 05:00:00    NaN
17 2016-11-16 06:00:00    NaN
18 2016-11-16 07:00:00    NaN
19 2016-11-16 08:00:00    NaN
20 2016-11-16 09:00:00   84.0

如果要填充那些 NaN 值,请使用 ffillbfillinterpolate

df.assign(
    Timestamp=pd.to_datetime(df.Timestamp, unit='ms')
).resample('H', on='Timestamp').mean().reset_index().interpolate()

             Timestamp   Value
0  2016-11-15 13:00:00  109.00
1  2016-11-15 14:00:00  107.75
2  2016-11-15 15:00:00  106.50
3  2016-11-15 16:00:00  105.25
4  2016-11-15 17:00:00  104.00
5  2016-11-15 18:00:00  102.75
6  2016-11-15 19:00:00  101.50
7  2016-11-15 20:00:00  100.25
8  2016-11-15 21:00:00   99.00
9  2016-11-15 22:00:00   97.75
10 2016-11-15 23:00:00   96.50
11 2016-11-16 00:00:00   95.25
12 2016-11-16 01:00:00   94.00
13 2016-11-16 02:00:00   92.75
14 2016-11-16 03:00:00   91.50
15 2016-11-16 04:00:00   90.25
16 2016-11-16 05:00:00   89.00
17 2016-11-16 06:00:00   87.75
18 2016-11-16 07:00:00   86.50
19 2016-11-16 08:00:00   85.25
20 2016-11-16 09:00:00   84.00