我计划对组间的多个变量进行 kruskal-wallis 检验(例如,out1、out2 和 out3 在序数水平上的疾病差异),并根据递减的 KW 测试结果获得排序的变量 [例如 out2、out3、out1]。但是,收到错误消息:“ValueError: If using all scalar values, you must pass an index”。那么如何解决呢?
from scipy import stats
import pandas as pd
import numpy as np
data = pd.DataFrame({ 'ID': list(range(1,21)),
'Disease': ["Cancer","Healthy","Adenoma","Cancer","Cancer","Healthy","Cancer","Healthy","Cancer","Cancer","Adenoma","Cancer","Healthy","Cancer","Healthy","Healthy","Healthy","Inflammation","Healthy","Inflammation"],
'Out1': np.random.randn(20),
'Out2': np.random.randn(20),
'Out3': np.random.randn(20)})
def KW_test(y, x):
y = np.array(y)
label, idx = np.unique(list(x), return_inverse=True)
groups = [y[idx == i] for i, l in enumerate(label)]
H, p = stats.kruskal(*groups)
return H
results=[]
outcomes= list(data.columns)[2:]
for i in outcomes:
y=data[i]
x=data.iloc[:, 1]
KW_test=KW_test(y,x)
results=pd.DataFrame({'outcomes': i, 'KW_test': KW_test}, columns=['outcomes', 'KW_test'])
results.append(results)
# sorted the results decreasingly using KW_test results
results=results.sort_value(["KW_test"], ascending=False)
# return the sorted outcomes
print(results[outcomes])