为什么 groupby 和 rolling 不能一起工作?

Why is groupby and rolling not working together?

我有一个从 coinmarketcap 中抓取的 df。我正在尝试计算 close_price 列的波动率指标,但是当我使用 groupby 时,我收到一条错误消息:

final_coin_data['vol'] = final_coin_data.groupby('coin_name')['close_price'].rolling(window=30).std()
TypeError: incompatible index of inserted column with frame index

df 结构('Unnamed:0' 在我加载 CSV 后出现):

    Unnamed: 0  close_price coin_name   date            high_price  low_price    market_cap         open_price  volume
0   1           9578.63     Bitcoin     Mar 11, 2018    9711.89     8607.12      149,716,000,000    8852.78     6,296,370,000
1   2           8866.00     Bitcoin     Mar 10, 2018    9531.32     8828.47      158,119,000,000    9350.59     5,386,320,000
2   3           9337.55     Bitcoin     Mar 09, 2018    9466.35     8513.03      159,185,000,000    9414.69     8,704,190,000
3   1           9578.63     Monero      Mar 11, 2018    9711.89     8607.12      149,716,000,000    8852.78     6,296,370,000
4   2           8866.00     Monero      Mar 10, 2018    9531.32     8828.47      158,119,000,000    9350.59     5,386,320,000
5   3           9337.55     Monero      Mar 09, 2018    9466.35     8513.03      159,185,000,000    9414.69     8,704,190,000

(忽略不正确的价格,这是df的基础)

使用以下代码时:

final_coin_data1['vol'] = final_coin_data.groupby('coin_name')['close_price'].rolling(window=30).std().reset_index(0,drop=True)

我遇到了内存错误。我以为我正确使用了 groupby。如果我取出 final_coin_data1['vol'] = 然后我得到一个看起来正确的系列,但它不会让我插入回 df.

当我第一次开始这个项目的时候。我只有 1 个硬币并使用下面的代码计算波动率没问题。

 final_coin_data1['vol'] = final_coin_data['close_price'].rolling(window=30).std()

当我运行这个,

final_coin_data['close_price'].rolling(window=30).std()

生成索引列和结果列。当我试图合并回原来的 df 作为一个新列时 final_coin_data1['vol'] 我得到了一个错误 TypeError: incompatible index of inserted column with frame index 所以为了更正这个问题,我 reset_index(drop=True) 然后这消除了允许结果的索引加入 final_coin_data1['vol'].

最终的功能代码如下所示:

final_coin_data1['vol'] = final_coin_data.groupby('coin_name')['close_price'].rolling(window=30).std().reset_index(0,drop=True)