我有以下DataFrame df
:
TIME DELAY
0 2016-01-01 06:30:00 0
1 2016-01-01 14:10:00 2
2 2016-01-01 07:05:00 2
3 2016-01-01 11:00:00 1
4 2016-01-01 10:40:00 0
5 2016-01-01 08:10:00 7
6 2016-01-01 11:35:00 2
7 2016-01-02 13:50:00 2
8 2016-01-02 14:50:00 4
9 2016-01-02 14:05:00 1
请注意,该行未按日期时间对象排序。
对于每一行,我想知道最近2小时的平均延迟。为此,我执行了以下代码:
df.index = pd.DatetimeIndex(df["TIME"])
df["DELAY_LAST2HOURS"] = df["DELAY"].rolling("2H").mean()
但是我遇到了这个错误:
ValueError: index must be monotonic
如何正确解决任务?
答案 0 :(得分:1)
问题是DatetimeIndex
未排序,因此需要DataFrame.sort_index
:
df.index = pd.DatetimeIndex(df["TIME"])
df = df.sort_index()
df["DELAY_LAST2HOURS"] = df["DELAY"].rolling("2H").mean()
print (df)
TIME DELAY DELAY_LAST2HOURS
TIME
2016-01-01 06:30:00 2016-01-01 06:30:00 0 0.000000
2016-01-01 07:05:00 2016-01-01 07:05:00 2 1.000000
2016-01-01 08:10:00 2016-01-01 08:10:00 7 3.000000
2016-01-01 10:40:00 2016-01-01 10:40:00 0 0.000000
2016-01-01 11:00:00 2016-01-01 11:00:00 1 0.500000
2016-01-01 11:35:00 2016-01-01 11:35:00 2 1.000000
2016-01-01 14:10:00 2016-01-01 14:10:00 2 2.000000
2016-01-02 13:50:00 2016-01-02 13:50:00 2 2.000000
2016-01-02 14:05:00 2016-01-02 14:05:00 1 1.500000
2016-01-02 14:50:00 2016-01-02 14:50:00 4 2.333333
如果没有必要,所有内容在一起都应为原始TIME
列:
df["TIME"] = pd.to_datetime(df["TIME"])
df = df.set_index('TIME').sort_index()
df["DELAY_LAST2HOURS"] = df["DELAY"].rolling("2H").mean()
print (df)
DELAY DELAY_LAST2HOURS
TIME
2016-01-01 06:30:00 0 0.000000
2016-01-01 07:05:00 2 1.000000
2016-01-01 08:10:00 7 3.000000
2016-01-01 10:40:00 0 0.000000
2016-01-01 11:00:00 1 0.500000
2016-01-01 11:35:00 2 1.000000
2016-01-01 14:10:00 2 2.000000
2016-01-02 13:50:00 2 2.000000
2016-01-02 14:05:00 1 1.500000
2016-01-02 14:50:00 4 2.333333
编辑:
df["TIME"] = pd.to_datetime(df["TIME"])
df = df.sort_values('TIME').set_index('TIME')
df["DELAY_LAST2HOURS"] = df["DELAY"].rolling("2H").mean()