使用 python 从存在或不存在不同基因的受试者列表中创建矩阵

creating a matrix from from a list of subjects with different genes present or absent with python

我有一个包含不同主题的文件,其中包含每个主题存在的基因列表(每个基因换行)。我想将数据重组为一个矩阵,行中包含不同的主题,然后是每个存在的基因的列(1 或 0 表示存在或不存在)。我将原始数据作为 excel 文件使用 pandas 导入,以尝试使用 Python 执行此操作。但老实说,我不知道如何以一种好的方式做到这一点。

image of how the data is structured and of how it is supposed to be formatted.

非常感谢能得到的所有帮助!

非常感谢

使用pivot()

df['count'] = 1
df.pivot(index='Subject', columns='Gene', values='count')

Gene       gene1    gene2   gene3   gene4   gene5
Subject                 
subject1    1.0      1.0    1.0      NaN    NaN
subject2    1.0      NaN    NaN      1.0    NaN
subject3    NaN      1.0    NaN      1.0    1.0

已更新 -- 完整示例基于您的评论

# import pandas module
import pandas as pd
import numpy as np

# read your excel file
df = pd.read_excel(r'path\to\your\file\myFile.xlsx')

# create a new column call 'count' and set it to a value of 1
df['count'] = 1

# use pivot and assign it to a new variable: df2
df2 = df.pivot(index='Subject', columns='Gene', values='count').replace(np.nan, 0)

# print your new dataframe
print(df2)

如果这是你的文件原文件:

Subject,Gene
subject1,gene1
subject1,gene2
subject1,gene3
subject2,gene1
subject2,gene4
subject3,gene2
subject3,gene4
subject3,gene5

然后你可以用pd.crosstab做这样的事情:

>>> import pandas as pd
>>> df = pd.read_csv("genes.csv")
>>> pd.crosstab(df["Subject"], df["Gene"])
Gene      gene1  gene2  gene3  gene4  gene5
Subject                                    
subject1      1      1      1      0      0
subject2      1      0      0      1      0
subject3      0      1      0      1      1