我正在处理库存数据,我试图在最近15分钟内获得“最后”值的最大值(最大值)。这显示在名为Max。的预期输出中。
我尝试的代码要花很长时间才能计算出来,所以我肯定缺少一些东西。由于我是时间序列的熊猫计算新手,因此不确定如何执行此操作。任何人都可以给您解决方案。谢谢
尝试过的代码:
for c in df["Last"].dropna():
df[c]=df["Last"].fillna(0).rolling('15T').max()
new="Prev15max_min"+df["Last"].dropna()
df.loc[:df.index[0]+pd.DateOffset(minutes=15),new]=np.nan
我的数据如下所示
Timestamp Last
1/20/19 12:15 3071.56
1/20/19 12:17 3097.82
1/20/19 12:17 3097.82
1/20/19 12:18 3095.25
1/20/19 12:19 3087.42
1/20/19 12:20 3095.29
1/20/19 12:21 3095.25
1/20/19 12:22 3093.11
1/20/19 12:23 3103
1/20/19 12:24 3095
1/20/19 12:25 3100.6
1/20/19 12:26 3099.84
1/20/19 12:27 3098.77
1/20/19 12:29 3097.24
1/20/19 12:29 3090
1/20/19 12:30 3090
1/20/19 12:31 3094.2
预期输出
Timestamp Last Max
1/20/19 12:15 3071.56
1/20/19 12:17 3097.82
1/20/19 12:17 3097.82
1/20/19 12:18 3095.25
1/20/19 12:19 3087.42
1/20/19 12:20 3095.29
1/20/19 12:21 3095.25
1/20/19 12:22 3093.11
1/20/19 12:23 3103
1/20/19 12:24 3095
1/20/19 12:25 3100.6
1/20/19 12:26 3099.84
1/20/19 12:27 3098.77
1/20/19 12:29 3097.24
1/20/19 12:29 3090 3103
1/20/19 12:30 3090 3103
1/20/19 12:31 3094.29 3103
答案 0 :(得分:0)
使用pandas.to_datetime
和rolling.max
:
import pandas as pd
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
df = df.set_index('Timestamp')
df['max'] = df['Last'].rolling('15min', min_periods=15).max()
print(df)
输出:
Last max
Timestamp
2019-01-20 12:15:00 3071.56 NaN
2019-01-20 12:17:00 3097.82 NaN
2019-01-20 12:17:00 3097.82 NaN
2019-01-20 12:18:00 3095.25 NaN
2019-01-20 12:19:00 3087.42 NaN
2019-01-20 12:20:00 3095.29 NaN
2019-01-20 12:21:00 3095.25 NaN
2019-01-20 12:22:00 3093.11 NaN
2019-01-20 12:23:00 3103.00 NaN
2019-01-20 12:24:00 3095.00 NaN
2019-01-20 12:25:00 3100.60 NaN
2019-01-20 12:26:00 3099.84 NaN
2019-01-20 12:27:00 3098.77 NaN
2019-01-20 12:29:00 3097.24 NaN
2019-01-20 12:29:00 3090.00 3103.0
2019-01-20 12:30:00 3090.00 3103.0
2019-01-20 12:31:00 3094.20 3103.0
如果您希望Timestamp
作为列而不是索引,请添加:
df.reset_index(inplace=True)