我正在创建一个相关矩阵,我希望从中获得最大正相关性值.对corr()
个结果应用max()将只返回轴上的相关性的1.0,这是不需要的,因此目标是删除所有出现的1.0,然后运行max()
.我正在考虑在一个链式操作中这样做,可以使用_将中间结果输送到where()
操作,这确实会将1.0转换为NAS.但是,应用max()
作为链中的下一个操作仍然返回1.0,就好像它忽略了where()
的结果一样.
我对_ operator有什么不明白的吗?或者where()
在这种情况下是错误的函数?我在下面提供了完整的代码来重现这个问题.
# Set up the problem
import pandas as pd
import numpy as np
# raw data
raw_t = [
66.6, 36.4, 47.6, 17.0, 54.6, 21.0, 12.2, 13.6, 20.6, 55.4, 63.4, 69.0,
80.2, 26.2, 42.6, 31.8, 15.6, 27.8, 13.8, 22.0, 14.2, 62.6, 96.4, 113.8,
115.2,82.2, 65.0, 23.2, 24.0, 14.2, 1.4, 3.8, 16.4, 16.4, 67.0, 51.4
]
# raw indexes
yr_mn = (np.full(12, 2000).tolist() + np.full(12, 2001).tolist() + np.full(12, 2002).tolist(),
np.arange(1,13).tolist() + np.arange(1,13).tolist() + np.arange(1,13).tolist() )
# structure multi index
index_base = list(zip(*yr_mn))
index = pd.MultiIndex.from_tuples(index_base, names=["year", "month"])
# create indexed dataset
t_dat = pd.Series(raw_t, index=index)
# example of the correlation matrix we are working with
pd.set_option("format.precision", 2)
t_dat.unstack().corr().style.background_gradient(cmap="YlGnBu")
我的try 是:
t_dat.unstack().corr().stack().where(_!=1.0) # does swap out 1.0 for NaN
t_dat.unstack().corr().stack().where(_!=1.0).max() # still returns 1.0
另一点是,它有时会起作用,但有时不会,返回
ValueError: Array conditional must be same shape as self
个
这也让我怀疑我错过了什么.Pandas max()
的默认设置是跳过NAN,所以它应该与此无关.我还try 使用where(_!=1.0,0.0)
将1.0设置为0.0;结果相同.此外,我发现如果我删除Where并重新运行,ValueError是可以克服的,如下所示:
t_dat.unstack().corr().stack()#.where(\_!=1.0)
这会以某种方式重置它,即使原始数据帧没有被更改.
感谢您的真知灼见! 大卫