数据框中所有行的 Pearson 相关性 Pandas

Pearson correlation for all rows in Data Frames Pandas

我在 Pandas 中有一个数据框,它的形状是 (136, 1445)。我尝试为我的 136 行创建相关(Pearson)矩阵。所以在结果中,我需要一个大小为 136x136 的矩阵。

我尝试了两种不同的方法,但无法从中获得结果,或者当我创建 136x136 相关矩阵时,我丢失了数据帧的列名。

首先,

gene_expression = pd.read_csv('padel_all_drug_results_original.csv',dtype='unicode')
gene_expression = gene_expression.convert_objects(convert_numeric=True)
gene_expression.corr()

这给出了基于列的 pearson 相关矩阵 (1445*1445),当我尝试转置我的数据框然后尝试找到相关性时,数据框的结构被破坏了(比如列名丢失或者我没有甚至确定相关性是否正确)。

其次,

distance = lambda column1, column2: pearsonr(column1,column2)[0]
result = gene_expression.apply(lambda col1: gene_expression.apply(lambda col2: distance(col1, col2)))

我应该怎么做才能计算 136x136 皮尔逊相关矩阵而不改变原始数据帧?

另外,我有 1445 个特征和一些几乎全是零的列。所以我放弃了那些列,因为它们是嘈杂的列,但你有另一个减少特征的想法吗?

提前致谢

要获得包含所有行之间成对相关的相关矩阵,您可以:

gene_expression.T.corr()

使用玩具示例:

df = pd.DataFrame(np.random.randint(0, high=100, size=(5, 10)), index=list(string.ascii_lowercase[:5]))

5 行和 10 列:

df.info()
Index: 5 entries, a to e
Data columns (total 10 columns):
0    5 non-null int64
1    5 non-null int64
2    5 non-null int64
3    5 non-null int64
4    5 non-null int64
5    5 non-null int64
6    5 non-null int64
7    5 non-null int64
8    5 non-null int64
9    5 non-null int64
dtypes: int64(10)
memory usage: 440.0+ bytes

使用

df.T.corr()

产量

          a         b         c         d         e
a  1.000000  0.209460 -0.205302 -0.294427  0.353803
b  0.209460  1.000000 -0.530715 -0.117949  0.775848
c -0.205302 -0.530715  1.000000 -0.245101 -0.344358
d -0.294427 -0.117949 -0.245101  1.000000  0.058302
e  0.353803  0.775848 -0.344358  0.058302  1.000000