如何获取熊猫中列列表的 p 值和皮尔逊 r?



我试图使相关系数的多索引表(矩阵)假定值。我更喜欢用scipy.stats测试。

x = pd.DataFrame(
list(
zip(
[1,2,3,4,5,6], [5, 7, 8, 4, 2, 8], [13, 16, 12, 11, 9, 10]
)
),
columns= ['a', 'b', 'c'] 
)

# I've tried something like this
for i in range(len(x.columns)):
r,p = pearsonr(x[x.columns[i]], x[x.columns[i+1]])
print(f'{r}, {p}')

显然for loop不会工作。最后我想写的是:

<表类>bctbody><<tr>r1.0.09点。8p高楼">.87点0。06br.09点1。p.87点高楼">.41点cr。8。1p0。06.41点00

下面是使用scipy person和Pandas corr方法的一种方法:

import pandas as pd
from scipy.stats import pearsonr
def pearsonr_pval(x, y):
return pearsonr(x, y)[1]

df = (
pd.concat(
[
x.corr(method="pearson").reset_index().assign(value="r"),
x.corr(method=pearsonr_pval).reset_index().assign(value="p"),
]
)
.groupby(["index", "value"])
.agg(lambda x: list(x)[0])
).sort_index(ascending=[True, False])
df.index.names = ["", ""]

:

print(df)
# Output
a         b         c
a r  1.000000 -0.088273 -0.796421
p  1.000000  0.867934  0.057948
b r -0.088273  1.000000  0.421184
p  0.867934  1.000000  0.405583
c r -0.796421  0.421184  1.000000
p  0.057948  0.405583  1.000000

最新更新