Pandas链式操作中_管道中间结果调用问题及最大值计算异常
从相关矩阵中获取排除自相关的最大正相关值问题
问题描述
我想要从相关矩阵中获取最大正相关值。直接对corr()的结果调用max()会返回轴上的1.0(即对角线的自相关值),不符合需求,因此目标是先移除所有1.0的值,再执行max()。
我尝试通过链式操作实现,使用_将中间结果传入where()操作,该操作确实能将1.0替换为NaN,但在链式操作的下一步调用max()时,仍返回1.0,仿佛忽略了where()的处理结果。
我是否对_运算符存在误解?或者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")
尝试代码与遇到的问题
我尝试的链式操作代码如下:
t_dat.unstack().corr().stack().where(_!=1.0) # 确实将1.0替换为NaN t_dat.unstack().corr().stack().where(_!=1.0).max() # 仍返回1.0
另外,该操作有时可行,有时会返回错误:ValueError: Array conditional must be same shape as self
我知道Pandas的max()默认会跳过NaN,所以问题应该不在这。我还尝试用where(_!=1.0,0.0)将1.0设为0.0,结果依旧返回1.0。此外,我发现若注释掉where()并重新运行:
t_dat.unstack().corr().stack()#.where(_!=1.0)
可以解决这个ValueError错误,尽管原DataFrame并未被修改。
感谢您的任何见解!
内容的提问来源于stack exchange,提问作者David A
相关产品推荐
相关产品推荐

