如何找到熊猫相关矩阵中的顶级相关性?关于如何用R(Show correlations as an ordered list, not as a large matrix或Efficient way to get highly correlated pairs from large data set in Python or R)做这个问题有很多答案,但我想知道如何用熊猫做到这一点?在我的情况下矩阵是4460x4460,所以不能在视觉上做到这一点。列出熊猫中大相关矩阵的最高相关对?
回答
您可以使用DataFrame.values
获取数据的一个numpy数组,然后使用NumPy函数(如argsort()
)获取最相关的对。
但是,如果你想这样做的熊猫,你可以unstack
和order
数据框:
import pandas as pd
import numpy as np
shape = (50, 4460)
data = np.random.normal(size=shape)
data[:, 1000] += data[:, 2000]
df = pd.DataFrame(data)
c = df.corr().abs()
s = c.unstack()
so = s.order(kind="quicksort")
print so[-4470:-4460]
这里是输出:
2192 1522 0.636198
1522 2192 0.636198
3677 2027 0.641817
2027 3677 0.641817
242 130 0.646760
130 242 0.646760
1171 2733 0.670048
2733 1171 0.670048
1000 2000 0.742340
2000 1000 0.742340
dtype: float64
@ HYRY的答案是完美的。只是建立在这个答案通过增加多一点的逻辑,以避免重复和自相关性和适当的排序:
import pandas as pd
d = {'x1': [1, 4, 4, 5, 6],
'x2': [0, 0, 8, 2, 4],
'x3': [2, 8, 8, 10, 12],
'x4': [-1, -4, -4, -4, -5]}
df = pd.DataFrame(data = d)
print("Data Frame")
print(df)
print()
print("Correlation Matrix")
print(df.corr())
print()
def get_redundant_pairs(df):
'''Get diagonal and lower triangular pairs of correlation matrix'''
pairs_to_drop = set()
cols = df.columns
for i in range(0, df.shape[1]):
for j in range(0, i+1):
pairs_to_drop.add((cols[i], cols[j]))
return pairs_to_drop
def get_top_abs_correlations(df, n=5):
au_corr = df.corr().abs().unstack()
labels_to_drop = get_redundant_pairs(df)
au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)
return au_corr[0:n]
print("Top Absolute Correlations")
print(get_top_abs_correlations(df, 3))
这让下面的输出:
Data Frame
x1 x2 x3 x4
0 1 0 2 -1
1 4 0 8 -4
2 4 8 8 -4
3 5 2 10 -4
4 6 4 12 -5
Correlation Matrix
x1 x2 x3 x4
x1 1.000000 0.399298 1.000000 -0.969248
x2 0.399298 1.000000 0.399298 -0.472866
x3 1.000000 0.399298 1.000000 -0.969248
x4 -0.969248 -0.472866 -0.969248 1.000000
Top Absolute Correlations
x1 x3 1.000000
x3 x4 0.969248
x1 x4 0.969248
dtype: float64
而不是get_redundant_pairs(df),可以使用“cor.loc [:,:] = np.tril(cor.values,k = -1)”,然后是“cor = cor [cor> 0]” – Sarah
几行方案,不会对冗余的变量:
corr_matrix = df.corr().abs()
#the matrix is symmetric so we need to extract upper triangle matrix without diagonal (k = 1)
os = (corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
.stack()
.order(ascending=False))
#first element of os series is the pair with the bigest correlation
使用itertools.combinations
摆脱熊猫自己的相关矩阵.corr()
所有独特的相关性,生成列表的列表并将其反馈回DataFrame以便使用'.sort_values'。设置ascending = True
以在顶部显示最低的相关性
corrank
将DataFrame作为参数,因为它需要.corr()
。
def corrank(X):
import itertools
df = pd.DataFrame([[(i,j),X.corr().loc[i,j]] for i,j in list(itertools.combinations(X.corr(), 2))],columns=['pairs','corr'])
print(df.sort_values(by='corr',ascending=False))
corrank(X) # prints a descending list of correlation pair (Max on top)
代码片段可能是解决方案,[包括解释](// meta.stackexchange.com/questions/114762/explaining-entirely-基于代码的答案)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 – haindl
- 1. 熊猫:如何从相关矩阵中删除自相关
- 2. 大熊猫:获取列的组合,其中相关性较高
- 3. 相关矩阵
- 4. 与大熊猫的互相关(时滞 - 相关)?
- 5. python中的相关矩阵
- 6. 对于R中对相关矩阵环
- 7. 从火花中的相关矩阵提取成对相关
- 8. 创建相关的熊猫系列
- 9. 矩阵与熊猫数据帧相反
- 10. 矩阵的相关系数
- 11. R:矩阵的自相关
- 12. Python的 - 从相关矩阵
- 13. 滑动矩阵的相关
- 14. 列置换的矩阵相关
- 15. 大熊猫排序相关列到第一列
- 16. 使用相关矩阵的大型稀疏矩阵上的PCA
- 17. 中等大小阵列的互相关
- 18. 加权相关矩阵
- 19. 索引相关矩阵
- 20. 交互相关矩阵
- 21. 相关两个矩阵
- 22. 如何对称排序相关矩阵?
- 23. 两个矩阵特征的高效配对相关
- 24. 大熊猫数据框中列的最大值相乘
- 25. 大矩阵中最大的相等子矩阵
- 26. 大熊猫阵列
- 27. 熊猫SUMIFS,行相关的过滤器
- 28. 与阵列相关
- 29. python中的矩阵相关计算
- 30. R中的秩相关矩阵
随着Pandas v 0.17.0及更高版本,您应该使用sort_values而不是order。如果您尝试使用订单方法,您将会遇到错误。 – Friendm1