[英]More succinct way to write a pandas moving average for several columns
I have a df with four columns as below:我有一个四列的df,如下所示:
A![]() |
B![]() |
C ![]() |
D ![]() |
---|---|---|---|
2 ![]() |
55 ![]() |
45 ![]() |
23 ![]() |
3 ![]() |
78 ![]() |
78 ![]() |
20 ![]() |
... ...
I would like to take a moving average of all of the columns with new names, and keep the original columns too.我想对所有具有新名称的列进行移动平均,并保留原始列。 I can do this using:
我可以这样做:
cols=['A','B','C','D']
df[cols].rolling(window=28, min_periods=14).mean().join(df, rsuffix='x').rename(columns={'A':'28d_A','B':'28d_B','C':'28d_C','D':'28d_D'})
Is there a better way which doesn't require me to rename all the columns and do a join?有没有更好的方法不需要我重命名所有列并进行连接? Thanks
谢谢
You can us a dict comprehension to assign()
.您可以对
assign()
使用dict理解。 Sample data is too short for output to be meaningful.样本数据太短,output 没有意义。
cols=['A','B','C','D']
df.assign(**{f"28d_{c}":df[c].rolling(window=28, min_periods=14).mean() for c in cols})
``
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.