在分析数据集后,我们如何查找所有属性的相关系数?
correlations = data.corr(method='pearson')print(correlation>=0.50)
我没有得到正确的结果。
回答:
数据:
df.head():
A B C D E0 0.050562 0.499951 -0.995909 0.693599 -0.4183021 -1.584577 -0.647707 0.598575 0.332250 -1.1474772 0.618670 -0.087987 0.425072 0.332253 -1.1568163 0.350997 -0.606887 1.546979 0.723342 0.0461364 -0.982992 0.054433 0.159893 -1.208948 2.223360
df_cor:
A B C D EA 1.000000 -0.008658 -0.015977 -0.001219 -0.008043B -0.008658 1.000000 0.037419 -0.055335 0.057751C -0.015977 0.037419 1.000000 0.000049 0.057091D -0.001219 -0.055335 0.000049 1.000000 -0.017879E -0.008043 0.057751 0.057091 -0.017879 1.000000
# 检查相关系数绝对值大于0.05的情况。这里是`0.05`,您可以将其更改为`0.5`。df_cor[df_cor.abs() > .05].dropna(axis=1, how='all').replace(1., np.nan).dropna(how='all', axis=1).dropna(how='all', axis=0).apply(lambda x:x.dropna().to_dict() ,axis=1).to_dict()
{'B': {'D': -0.0553348494117175, 'E': 0.057751329924049855}, 'C': {'E': 0.057091148280687266}, 'D': {'B': -0.0553348494117175}, 'E': {'B': 0.057751329924049855, 'C': 0.057091148280687266}}
如果您需要数据框输出:
df_cor[df_cor.abs() > .05].replace(1, np.nan)
A B C D EA NaN NaN NaN NaN NaNB NaN NaN NaN -0.055335 0.057751C NaN NaN NaN NaN 0.057091D NaN -0.055335 NaN NaN NaNE NaN 0.057751 0.057091 NaN NaN
删除没有值的列后:
df_cor[df_cor.abs() > .05].replace(1, np.nan).dropna(how='all', axis=1)
B C D EA NaN NaN NaN NaNB NaN NaN -0.055335 0.057751C NaN NaN NaN 0.057091D -0.055335 NaN NaN NaNE 0.057751 0.057091 NaN NaN