[英]Apply function on a rolling basis within groupby in pandas
I have a dataframe that looks like the following. 我有一个数据框,如下所示。
symbol Range
Date
2018-08-16 spy 1.5
2018-08-17 spy 1.2
2018-08-16 spy 1.3
2018-08-17 spy 1.6
2017-07-17 spy 1.1
2017-07-18 spy 1.9
2018-08-16 nflx 4.5
2018-08-17 nflx 5.2
I have added a column that finds the 15th percentile of Range by doing the following: 我添加了一个列,该列通过执行以下操作找到Range的第15个百分位数:
df['Range_quantile'] = df.groupby(['symbol'])['Range'].transform(lambda x: np.percentile(x.unique(), 15))
As of a given row, how do I apply the same function only to the last 20 rows(within the group) on a rolling basis grouped by symbol
and then add back the output as a column( Range_quantile_rolling
) to the dataframe? 从给定的行开始,如何将相同的功能按
symbol
分组滚动地仅应用于最后20行(组内),然后将输出作为列( Range_quantile_rolling
)加回到数据Range_quantile_rolling
? My example applies the lambda x: np.percentile(x.unique(), 15)
function to the whole Range
column. 我的示例将
lambda x: np.percentile(x.unique(), 15)
函数应用于整个Range
列。
For example, if I am adding the function in the last 3 rows within groupby, it might look like this: 例如,如果我要在groupby的最后3行中添加函数,则它可能如下所示:
symbol Range Range_Quantile_Rolling_3
Date
2018-08-16 spy 1.5 NA
2018-08-17 spy 1.2 NA
2018-08-16 spy 1.3 1.21
2018-08-17 spy 1.6 1.25
2017-07-17 spy 1.1 1.15
2017-07-18 spy 1.9 1.3
2018-08-16 nflx 4.5 NA
2018-08-17 nflx 5.2 NA
groupby
and transform
with a lambda
groupby
并使用lambda
transform
df.assign(Range=df.groupby('symbol').Range.transform(
lambda x: x.rolling(3).apply(lambda y: np.percentile(np.unique(y), 15))
))
symbol Range
Date
2018-08-16 spy NaN
2018-08-17 spy NaN
2018-08-16 spy 1.23
2018-08-17 spy 1.23
2017-07-17 spy 1.16
2017-07-18 spy 1.25
2018-08-16 nflx NaN
2018-08-17 nflx NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.