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

标签 python pandas resampling

我有一个数据框:

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/

相关文章:

python - 检查 Google App Engine 模型中的属性类型

python - 如何比较两个列表并将差异复制到第三个列表(python)?

python - 模式后提取字符串

python - 绘制 Pandas 数据框的饼图和表格

python-3.x - python中的resample或asfreq pandas时间序列数据帧错误为 'Duplicate Index'

audio - 如何高频播放wav文件?

python - 在 python grpc 中我得到一个异常 “No match found for server name”

python - 我收到 ValueError : strftime format ends with raw % for root. Clipboard_append(d.strftime ("%I:%M %p"+% +"%"))

python - 创建新列来比较 pandas 数据框中的行

matlab - 重采样因子太大