【发布时间】:2021-12-03 14:12:33
【问题描述】:
我有一组这样的列:
q1_cash_total, q2_cash_total, q3_cash_total,
q1_shop_us, q2_shop_us, q3_shop_us,
等等,我有大约 40 个类似这样命名的列名。我希望计算每组 3 个之间的 pct 变化。例如我知道我可以做到:
df[['q1_cash_total', 'q2_cash_total', 'q3_cash_total']].pct_change().add_suffix('_PCT_CHG')
每做 3 次就这样做:
q1 = [col for col in df.columns if 'q1' in col ]
q2 = [col for col in df.columns if 'q2' in col ]
q3 = [col for col in df.columns if 'q3' in col ]
q_cols = q1+q2+q3
dflist = []
for col in df[q_cols].columns:
#col[3:] to just get col name without the q1_/q2_ etc
print(col[3:])
cols = [c for c in df.columns if col[3:] in c]
pct = df[cols].pct_change().add_suffix('_PCT_CHG')
dflist.append(pct)
pcts_df = pd.concat(dflist)
我想不出更清洁的方法来做到这一点。有人有什么想法吗?我怎样才能做到这一点,以便我也在 q1 和 q3 之间进行 pct 更改而不是连续进行。
【问题讨论】:
标签: python pandas dataframe percentage