在熊猫中,我有这样的数据集:
Value
2005-08-03 23:15:00 10.5
2005-08-03 23:30:00 10.0
2005-08-03 23:45:00 10.0
2005-08-04 00:00:00 10.5
2005-08-04 00:15:00 10.5
2005-08-04 00:30:00 11.0
2005-08-04 00:45:00 10.5
2005-08-04 01:00:00 11.0
...
2005-08-04 23:15:00 14.0
2005-08-04 23:30:00 13.5
2005-08-04 23:45:00 13.0
2005-08-05 00:00:00 13.5
2005-08-05 00:15:00 14.0
2005-08-05 00:30:00 14.0
2005-08-05 00:45:00 14.5
首先,我想按日期分组数据,并将每个组的最大值存储在新列中,为此任务我使用了以下代码:
^{pr2}$现在,我想创建另一列来存储先前的组最大值,因此所需的数据帧如下所示:
Value ValueMaxInGroup ValueMaxInPrevGroup
2005-08-03 23:15:00 10.5 10.5 NaN
2005-08-03 23:30:00 10.0 10.5 NaN
2005-08-03 23:45:00 10.0 10.5 NaN
2005-08-04 00:00:00 10.5 14.0 10.5
2005-08-04 00:15:00 10.5 14.0 10.5
2005-08-04 00:30:00 11.0 14.0 10.5
2005-08-04 00:45:00 10.5 14.0 10.5
2005-08-04 01:00:00 11.0 14.0 10.5
...
2005-08-04 23:15:00 14.0 14.0 10.5
2005-08-04 23:30:00 13.5 14.0 10.5
2005-08-04 23:45:00 13.0 14.0 10.5
2005-08-05 00:00:00 13.5 14.5 14.0
2005-08-05 00:15:00 14.0 14.5 14.0
2005-08-05 00:30:00 14.0 14.5 14.0
2005-08-05 00:45:00 14.5 14.5 14.0
所以,为了简单地得到前一行的值,我使用
df['ValueInPrevRow'] = df.shift(1)['Value']
有没有办法得到另一组的最小/最大/f(x)?我以为
df['ValueMaxInPrevGroup'] = df.groupby(pd.TimeGrouper('D')).shift(1)['Value'].transform(max)
但没用。在
谢谢
您可以通过使用
groupby/agg
、shift
和merge
获得所需的结果:收益率
^{pr2}$这里的主要思想是用
groupby/agg
代替groupby/transform
,这样我们就可以得到然后,所需的数据帧可以表示为与
df
合并的结果 ^{cd7}日期。在相关问题 更多 >
编程相关推荐