为什么Groupby和Rolling不能一起工作? [英] Why is groupby and rolling not working together?

查看:49
本文介绍了为什么Groupby和Rolling不能一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从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结构(‘unname: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)

我遇到内存错误。我以为我用团购是正确的。如果我取出final_coin_data1['vol'] =,那么我会得到一个看起来正确的序列,但它不会让我重新插入到DF中。

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

 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)

这篇关于为什么Groupby和Rolling不能一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆