gpt4 book ai didi

python - 在 pct_change() 和缺失值之前重新采样

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:52 25 4
gpt4 key购买 nike

我有一个数据框:

import pandas as pd
df = pd.DataFrame([['A', 'G1', '2019-01-01', 11],
['A', 'G1', '2019-01-02', 12],
['A', 'G1', '2019-01-04', 14],
['B', 'G2', '2019-01-01', 11],
['B', 'G2', '2019-01-03', 13],
['B', 'G2', '2019-01-06', 16]],
columns=['cust', 'group', 'date', 'val'])
df

enter image description here

df = df.groupby(['cust', 'group', 'date']).sum()
df

enter image description here

数据框已分组,现在我想计算 pct_change,但前提是有以前的日期。如果我这样做:

df['pct'] = df.groupby(['cust', 'group']).val.pct_change()
df

enter image description here

我将获得 pct_change,但不考虑遗漏的日期。例如在 ('A', 'G1') 组中,日期 2019-01-04pct 应该是 np. nan 因为没有(先前的)日期 2019-01-03

也许解决方案是按天重新采样,其中每个新行都将 np.nan 作为 val,而不是执行 pct_change.

我尝试使用 df.resample('1D', level=2) 但我得到一个错误:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'

对于 ('B', 'G2') 组,所有 pct_change 都应该是 np.nan 因为没有行有之前的日期.

预期结果是:

enter image description here

如何根据缺失日期计算 pct_change

解决方法:

new_df = pd.DataFrame()

for x, y in df.groupby(['cust', 'group']):
resampled=y.set_index('date').resample('D').val.mean().to_frame().rename({'val': 'resamp_val'}, axis=1)
resampled = resampled.join(y.set_index('date')).fillna({'cust':x[0],'group':x[1]})
resampled['resamp_val_pct'] = resampled.resamp_val.pct_change(fill_method=None)

new_df = pd.concat([new_df, resampled])

new_df = new_df[['cust', 'group', 'val', 'resamp_val', 'resamp_val_pct']]
new_df

enter image description here

最佳答案

检查 groupby,然后您需要先resample 并使用 bool 掩码获取 pct 变化,因为 pct_change 将忽略 NaN

d={}
for x, y in df.groupby(['cust', 'group']):
s = y.set_index('date').resample('D').val.mean()
d[x] = pd.concat([s, s.pct_change().mask(s.shift().isnull()|s.isnull())], 1)
newdf = pd.concat(d)
newdf.columns = ['val', 'pct']
newdf
Out[651]:
val pct
date
A G1 2019-01-01 11.0 NaN
2019-01-02 12.0 0.090909
2019-01-03 NaN NaN
2019-01-04 14.0 NaN
B G2 2019-01-01 11.0 NaN
2019-01-02 NaN NaN
2019-01-03 13.0 NaN
2019-01-04 NaN NaN
2019-01-05 NaN NaN
2019-01-06 16.0 NaN

可以在末尾添加reset_index(inplace=True)让所有的索引都变回列

关于python - 在 pct_change() 和缺失值之前重新采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54255901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com