gpt4 book ai didi

python - 生成PCA加载矩阵时如何将pandas dataframe列设置为索引

转载 作者:行者123 更新时间:2023-12-01 07:26:28 28 4
gpt4 key购买 nike

我正在 python 中使用 sklearn 对基因表达数据执行主成分分析 (PCA)。我的数据作为 pandas 数据帧加载,我可以调用 df.head() 并且 df 看起来不错。我正在使用 sklearn 生成加载矩阵,但该矩阵仅显示通用索引,并且不接受索引的列名称。我有 1722 个基因,因此通过计算获得每个基因的加载分数非常重要。

这是我的 PCA 代码:

import pandas as pd
from sklearn.decomposition import PCA
from sklearn import preprocessing


# Load the data as pandas dataframe
cols = ['gene', 'FC_TSWV', 'FC_WFT', 'FC_TSWV_WFT']
df = pd.read_csv('./PCA.txt', names = cols, header = None, index_col = 'gene')

# preprocess data:

scaled_df = preprocessing.scale(df.T)


# perform PCA

pca = PCA()
pca.fit(scaled_df)
pca_data = pca.transform(scaled_df)


# Generate loading matrix. HERE IS WHERE THE TROUBLE IS:

loading_scores = pd.Series(pca.components_[0], index = df.gene)


# Print loading matrix

sorted_loading_scores = loading_scores.abs().sort_values(ascending=False)
print(loading_scores)

我已经尝试过:

loading_scores = pd.Series(pca.components_[0], index = df.gene)

loading_scores = pd.Series(pca.components_[0], index = df['gene'])

loading_scores = pd.Series(pca.components_[0], index = df.loc['gene']

属性错误:“DataFrame”对象没有属性“基因”。

如果我根本不指定索引,则加载分数将使用基于 0 的通用索引来指定。

有人知道如何解决这个问题吗?

最佳答案

使用df.index而不是df.genedf['gene']

一旦将某个列设置为索引,访问它的方式就是通过 .index 属性,而不再是通过列的名称。

关于python - 生成PCA加载矩阵时如何将pandas dataframe列设置为索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57421169/

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