gpt4 book ai didi

python scipy spearman相关性

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:56 27 4
gpt4 key购买 nike

我正在尝试从数据帧 (df) 中获取列名,并将它们关联到由 spearmanr 相关函数生成的结果数组。我需要将列名 (a-j) 关联回相关值 (spearman) 和 p 值 (spearman_pvalue)。是否有一种直观的方式来执行此任务?

from scipy.stats import pearsonr,spearmanr
import numpy as np
import pandas as pd

df=pd.DataFrame(np.random.randint(0,100,size= (100,10)),columns=list('abcdefghij'))

def binary(row):
if row>=50:
return 1
else:
return 0
df['target']=df.a.apply(binary)

spearman,spearman_pvalue=spearmanr(df.drop(['target'],axis=1),df.target)
print(spearman)
print(spearman_pvalue)

最佳答案

看来你需要:

from scipy.stats import spearmanr

df=pd.DataFrame(np.random.randint(0,100,size= (100,10)),columns=list('abcdefghij'))
#print (df)

#faster for binary df
df['target'] = (df['a'] >= 50).astype(int)
#print (df)

spearman,spearman_pvalue=spearmanr(df.drop(['target'],axis=1),df.target)

df1 = pd.DataFrame(spearman.reshape(-1, 11), columns=df.columns)
#print (df1)

df2 = pd.DataFrame(spearman_pvalue.reshape(-1, 11), columns=df.columns)
#print (df2)

### Kyle, we can assign the index back to the column names for the total matrix:
df2=df2.set_index(df.columns)
df1=df1.set_index(df.columns)

或者:

df1 = pd.DataFrame(spearman.reshape(-1, 11), 
columns=df.columns,
index=df.columns)
df2 = pd.DataFrame(spearman_pvalue.reshape(-1, 11),
columns=df.columns,
index=df.columns)

关于python scipy spearman相关性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47485203/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com