我正在尝试将如下所示的 z 分数 (axa)、(axb) 值转换为相关矩阵。
第一行各行相关矩阵如下所示:
有什么方法可以在 python 中轻松转换我的 csv 吗?转型后我应该能够做到:
import pandas as pd
con = pd.read_csv('Data/connectivity.csv')
# Do transform here
cormat = con.corr()
round(cormat,2)
sns.heatmap(cormat);
谢谢你。
凯文
假设这个输入:
a x a a x b a x c b x a b x b b x c c x a c x b c x c
0 1 0.315900 0.5391 0.315900 1 0.45100 0.53910 0.45100 1
1 1 0.387880 0.30813, 0.387880 1 0.33133 0.30813 0.33133 1
2 1 -0.021537 -0.30658 -0.021537 1 0.68163 -0.30658 0.68163 1
3 1 -0.001746 0.11458 -0.001746 1 0.39171 0.11458 0.39171 1
split
放入MultiIndex中:
tmp = df.set_axis(df.columns.str.split(' x ', expand=True), axis=1)
unstack
:
out = tmp.iloc[0].unstack()
输出:
a b c
a 1 0.3159 0.5391
b 0.3159 1 0.451
c 0.5391 0.451 1
要为每行构建一个新的数据框,可以循环:
dfs = [tmp.iloc[i].unstack() for i in range(tmp.shape[0])]
或者先 然后用 groupby
拆分:
dfs = [g for _, g in tmp.stack().groupby(level=0)]
输出:
[ a b c
0 a 1 0.3159 0.5391
b 0.3159 1.0000 0.4510
c 0.5391 0.4510 1.0000,
a b c
1 a 1 0.38788 0.30813
b 0.38788 1.00000 0.33133
c 0.30813, 0.33133 1.00000,
a b c
2 a 1 -0.021537 -0.30658
b -0.021537 1.000000 0.68163
c -0.30658 0.681630 1.00000,
a b c
3 a 1 -0.001746 0.11458
b -0.001746 1.000000 0.39171
c 0.11458 0.391710 1.00000]
中级tmp
:
a b c
a b c a b c a b c
0 1 0.315900 0.5391 0.315900 1 0.45100 0.53910 0.45100 1
1 1 0.387880 0.30813, 0.387880 1 0.33133 0.30813 0.33133 1
2 1 -0.021537 -0.30658 -0.021537 1 0.68163 -0.30658 0.68163 1
3 1 -0.001746 0.11458 -0.001746 1 0.39171 0.11458 0.39171 1
row_1_reshaped = con.iloc[0].values.reshape((3,3)) # this is the first row
row_2_reshaped = con.iloc[1].values.reshape((3,3)) # this is the second row