What I have:
Sym Date close
A 1-Jan 45
A 2-Jan 15
A 3-Jan 55
B 1-Jan 41
B 2-Jan 87
B 3-Jan 82
C 1-Jan 33
C 2-Jan 15
C 3-Jan 46
What I need
Sym Date close rolling_max_2day
A 1-Jan 45 NaN
A 2-Jan 15 45
A 3-Jan 55 55
B 1-Jan 41 NaN
B 2-Jan 87 87
B 3-Jan 82 87
C 1-Jan 33 NaN
C 2-Jan 15 33
C 3-Jan 46 46
The dataframe df
is with multiple index(Sym, Date)
I have tried like this:
df['rolling_max_2day'] = df.groupby(level=['sym']).apply(lambda x:pd.rolling_max(x['close'].values,2))
it does not return any errors, but it also returns all null value at column rolling_max_2day
However, if only this code, not append to df
, I can get a correct series.
df.groupby(level=['sym']).apply(lambda x:pd.rolling_max(x['close'].values,2))
Thanks!
You can apply on df.groupby('Sym')['close']
using pd.rolling_max(x, 2)
instead
In [124]: df['rolling_max_2day'] = (df.groupby('Sym')['close']
.apply(lambda x:pd.rolling_max(x, 2)))
In [125]: df
Out[125]:
Sym Date close rolling_max_2day
0 A 1-Jan 45 NaN
1 A 2-Jan 15 45
2 A 3-Jan 55 55
3 B 1-Jan 41 NaN
4 B 2-Jan 87 87
5 B 3-Jan 82 87
6 C 1-Jan 33 NaN
7 C 2-Jan 15 33
8 C 3-Jan 46 46
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.