python-3.x - 如何重新采样多索引数据帧内的数据

标签 python-3.x pandas dataframe datetime resampling

我有以下数据框:enter image description here

我需要重新采样数据来计算每周的 pct_change()。我怎样才能获得每周的变化?

类似 data['pct_week'] = data['Adj Close'].resample('W').ffill().pct_change()但是数据需要分组data.groupby(['month', 'week'])
这样每个月都会产生 4 个每周变化的值。然后我可以绘制

我所做的是df['pct_week'] = data['Adj Close'].groupby(['week', 'day']).pct_change()但我收到此错误 TypeError: 'type' object does not support item assignment

最佳答案

如果想先用 resample 分组是必要的 DatetimeIndex只有,所以添加
DataFrame.reset_index 通过所有级别而不先,然后使用自定义函数进行分组和重新采样,因为 pct_changeresample未实现:

def percent_change(x):
    return pd.Series(x).pct_change()

另一个想法是对 pct_change 使用 numpy 解决方案:
def percent_change(x):
    return x / np.concatenate(([np.nan], x[:-1])) - 1
df1 = (df.reset_index(level=[1,2,3])
        .groupby(['month', 'week'])['Adj Close']
        .resample('W')
        .apply(percent_change))

this way every month would yield 4 values for weekly change



所以似乎没有groupby ,只需要像 sum 这样的下采样和链 Series.pct_change :
df2 = (df.reset_index(level=[1,2,3])
        .resample('W')['Adj Close']
        .sum()
        .pct_change())

关于python-3.x - 如何重新采样多索引数据帧内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58696776/

相关文章:

python - 如何根据列的值和该列中的下一个值过滤数据帧的行

python - Pandas DataFrame 在复杂的 'if' 条件下使用前一行值来确定当前值

r - 查找同一列中不同类别的数据框中的匹配数

python - 如何对 csv 中的 'date' 列进行排序以仅显示年度范围的 Spring 数据

python - 重命名 Dataframe 中的列,前提是该列包含循环中的数据

python - 为什么 from tkinter import * 不导入 Tkinter 的消息框?

python - Pandas 数据框 : Split mixed float-string column into separate float and string columns

python - 在 Pandas 中,如何根据列中以逗号分隔的项目计数创建数据框?

python - 在 Python 3 中可以结合参数描述和类型提示吗?

python - 使用 Gunicorn 进行预测时无法解开对象