熊猫列列表之间的相关性X整个数据框
问题描述:
我正在寻找Pandas .corr()方法的帮助。熊猫列列表之间的相关性X整个数据框
由于是,我可以使用.corr()方法来计算列的每一个可能的组合的热图:
corr = data.corr()
sns.heatmap(corr)
其中,在我的23000列的数据帧,可热死近终止宇宙。
我还可以做值的子集之间的比较合理的相关性
data2 = data[list_of_column_names]
corr = data2.corr(method="pearson")
sns.heatmap(corr)
什么我想要做的就是比较20列的列表与整个数据集。正常的.corr()函数可以给我一个20x20或23,000x23,000热图,但本质上我想要一个20x23,000热图。
如何为我的相关性添加更多特异性?
感谢您的帮助!
答
通过这一昨晚工作后,我来到了以下的答案:
#datatable imported earlier as 'data'
#Create a new dictionary
plotDict = {}
# Loop across each of the two lists that contain the items you want to compare
for gene1 in list_1:
for gene2 in list_2:
# Do a pearsonR comparison between the two items you want to compare
tempDict = {(gene1, gene2): scipy.stats.pearsonr(data[gene1],data[gene2])}
# Update the dictionary each time you do a comparison
plotDict.update(tempDict)
# Unstack the dictionary into a DataFrame
dfOutput = pd.Series(plotDict).unstack()
# Optional: Take just the pearsonR value out of the output tuple
dfOutputPearson = dfOutput.apply(lambda x: x.apply(lambda x:x[0]))
# Optional: generate a heatmap
sns.heatmap(dfOutputPearson)
就像其他的答案,这会产生一个热图(见下文),但它可以扩展到允许一个20,000x30矩阵,而不计算整个20,000x20,000组合之间的相关性(因此终止速度更快)。
答
列出您想要的子集(在本例中为A,B和C),创建一个空数据框,然后使用嵌套循环填充所需值。
df = pd.DataFrame(np.random.randn(50, 7), columns=list('ABCDEFG'))
# initiate empty dataframe
corr = pd.DataFrame()
for a in list('ABC'):
for b in list(df.columns.values):
corr.loc[a, b] = df.corr().loc[a, b]
corr
Out[137]:
A B C D E F G
A 1.000000 0.183584 -0.175979 -0.087252 -0.060680 -0.209692 -0.294573
B 0.183584 1.000000 0.119418 0.254775 -0.131564 -0.226491 -0.202978
C -0.175979 0.119418 1.000000 0.146807 -0.045952 -0.037082 -0.204993
sns.heatmap(corr)
答
通常相关的计算系数成对所有变量做最有意义。 pd.corr()是便利函数,用于计算两两相关系数(以及所有对)。 你也可以用scipy来做,也仅限于循环中的指定对。
实施例:
在大熊猫d=pd.DataFrame([[1,5,8],[2,5,4],[7,3,1]], columns=['A','B','C'])
一对可以是:
d.corr().loc['A','B']
-0.98782916114726194
等效在SciPy的:
import scipy.stats
scipy.stats.pearsonr(d['A'].values,d['B'].values)[0]
-0.98782916114726194
谢谢你的有用评论!这看起来在理论上效果很好。实际上,它看起来像'corr = data.corr()。iloc [3:5,1:2]',它应该是一个相对简单的相关性,需要相当长的一段时间才能终止(它没有大约5到目前为止分钟)。我猜这是因为.corr()首先计算了我所有23,000行之间的相关性,然后再进行分片。 – CalendarJ
好的。我将编辑以展示如何做到这一点。 – Andrew
如果新更改解决了您的问题,请接受此答案。 – Andrew