【问题标题】:Pandas plot correlations熊猫图相关性
【发布时间】:2021-01-25 14:36:29
【问题描述】:

我一直在尝试使用 python 绘制股票随时间的成对相关性。我正在关注以下repository,但我似乎无法使滚动相关工作,我在这里收到错误:

correls = correls[(window-1):,:,:]

TypeError: '(slice(99, None, None), slice(None, None, None), slice(None, None, None))' is an invalid key

添加示例代码:

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date, periods=10, freq='D')
 
columns = ['A', 'B', 'C']
 
df = pd.DataFrame(index=index, columns=columns)
df = df.mask(df.isnull(), np.random.uniform(3, 331, size=df.shape))

window = 2                            #rolling correlation window length
correls = df.rolling(window=window).corr()
correls = correls[(window-1):,:,:] 

亲切的问候

【问题讨论】:

  • 您能否发布您使用的示例数据框和示例代码。谢谢。

标签: python pandas slice


【解决方案1】:

如果我理解正确,您尝试删除最后带有 NaN 的行。要做到这一点,请尝试

correls = correls[(window-1)*len(df.columns):]

而不是

correls = correls[(window-1):,:,:] 

【讨论】:

  • 谢谢玛丽亚,效果很好,我想问题是“相关”输出的尺寸。如果我想选择 A 和 B 之间的相关性,下面的代码行不通? sA = "A" sB = "B" correls.loc[:,sA,sB].plot()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 2014-10-23
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 2016-10-29
  • 2021-03-03
相关资源
最近更新 更多