如何在Pandas的相关矩阵中找到最高相关性?有关于如何有R做很多答案(显示相关性为有序列表,而不是作为一个大的矩阵或有效的方式来获得大量的数据在Python或R设置高度相关货币对),但我想知道如何做到这一点与熊猫?在我的情况下,矩阵是4460x4460,所以不能在视觉上做.
HYR*_*YRY 72
您可以使用DataFrame.values获取数据的numpy数组,然后使用NumPy函数argsort()来获取最相关的对.
但是如果你想在熊猫中这样做,你可以unstack和orderDataFrame一起:
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.sort_values(kind="quicksort")
print so[-4470:-4460]
Run Code Online (Sandbox Code Playgroud)
这是输出:
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
Run Code Online (Sandbox Code Playgroud)
aru*_*run 32
@ 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))
Run Code Online (Sandbox Code Playgroud)
这给出了以下输出:
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
Run Code Online (Sandbox Code Playgroud)
MiF*_*iFi 25
没有冗余变量对的几行解决方案:
corr_matrix = df.corr().abs()
#the matrix is symmetric so we need to extract upper triangle matrix without diagonal (k = 1)
sol = (corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
.stack()
.sort_values(ascending=False))
#first element of sol series is the pair with the bigest correlation
Run Code Online (Sandbox Code Playgroud)
pra*_*nth 11
使用下面的代码按降序查看相关性。
# See the correlations in descending order
corr = df.corr() # df is the pandas dataframe
c1 = corr.abs().unstack()
c1.sort_values(ascending = False)
Run Code Online (Sandbox Code Playgroud)
Woj*_*ski 10
您可以根据这个简单的代码通过替换您的数据以图形方式进行。
corr = df.corr()
kot = corr[corr>=.9]
plt.figure(figsize=(12,8))
sns.heatmap(kot, cmap="Greens")
Run Code Online (Sandbox Code Playgroud)
Jam*_*goe 10
我最喜欢 Addison Klinke 的帖子,因为它是最简单的,但使用了 Wojciech Moszczy?sk 的过滤和图表建议,但扩展了过滤器以避免绝对值,因此给定一个大的相关矩阵,过滤它,绘制它,然后将其展平它:
创建、过滤和绘制
dfCorr = df.corr()
filteredDf = dfCorr[((dfCorr >= .5) | (dfCorr <= -.5)) & (dfCorr !=1.000)]
plt.figure(figsize=(30,10))
sn.heatmap(filteredDf, annot=True, cmap="Reds")
plt.show()
Run Code Online (Sandbox Code Playgroud)
功能
最后,我创建了一个小函数来创建相关矩阵,对其进行过滤,然后将其展平。作为一个想法,它可以很容易地扩展,例如,不对称的上下界等。
def corrFilter(x: pd.DataFrame, bound: float):
xCorr = x.corr()
xFiltered = xCorr[((xCorr >= bound) | (xCorr <= -bound)) & (xCorr !=1.000)]
xFlattened = xFiltered.unstack().sort_values().drop_duplicates()
return xFlattened
corrFilter(df, .7)
Run Code Online (Sandbox Code Playgroud)
跟进
最后,我完善了功能
# Returns correlation matrix
def corrFilter(x: pd.DataFrame, bound: float):
xCorr = x.corr()
xFiltered = xCorr[((xCorr >= bound) | (xCorr <= -bound)) & (xCorr !=1.000)]
return xFiltered
# flattens correlation matrix with bounds
def corrFilterFlattened(x: pd.DataFrame, bound: float):
xFiltered = corrFilter(x, bound)
xFlattened = xFiltered.unstack().sort_values().drop_duplicates()
return xFlattened
# Returns correlation for a variable from flattened correlation matrix
def filterForLabels(df: pd.DataFrame, label):
try:
sideLeft = df[label,]
except:
sideLeft = pd.DataFrame()
try:
sideRight = df[:,label]
except:
sideRight = pd.DataFrame()
if sideLeft.empty and sideRight.empty:
return pd.DataFrame()
elif sideLeft.empty:
concat = sideRight.to_frame()
concat.rename(columns={0:'Corr'},inplace=True)
return concat
elif sideRight.empty:
concat = sideLeft.to_frame()
concat.rename(columns={0:'Corr'},inplace=True)
return concat
else:
concat = pd.concat([sideLeft,sideRight], axis=1)
concat["Corr"] = concat[0].fillna(0) + concat[1].fillna(0)
concat.drop(columns=[0,1], inplace=True)
return concat
Run Code Online (Sandbox Code Playgroud)
结合@HYRY和@ arun的答案的一些功能,您可以df使用以下方法在一行中打印数据帧的最高相关性:
df.corr().unstack().sort_values().drop_duplicates()
Run Code Online (Sandbox Code Playgroud)
注意:一个缺点是如果你有1.0个不是自身变量的相关性,那么drop_duplicates()加法就会删除它们
| 归档时间: |
|
| 查看次数: |
58551 次 |
| 最近记录: |