gpt4 book ai didi

python - Pandas:基于字典分割和编辑文件

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:49 25 4
gpt4 key购买 nike

我是 pandas 新手,在解决以下问题时遇到了一些麻烦。我需要使用两个文件来创建输出。第一个文件包含功能和相关基因的列表。文件示例(显然数据完全是虚构的)

File 1:

Function Genes
Emotions HAPPY,SAD,GOOFY,SILLY
Walking LEG,MUSCLE,TENDON,BLOOD
Singing VOCAL,NECK,BLOOD,HAPPY

我正在使用以下方法读字典:

from collections import *

FunctionsWithGenes = defaultdict(list)

def read_functions_file(File):
Header = File.readline()
Lines = File.readlines()
for Line in Lines:
Function, Genes = Line[0], Line[1]
FunctionsWithGenes[Function] = Genes.split(",") # the genes for each function are in the same row and separated by commas

第二个表包含我在包含一列基因的 .txt 文件中需要的所有信息例如:

chr    start    end    Gene    Value   MoreData
chr1 123 123 HAPPY 41.1 3.4
chr1 342 355 SAD 34.2 9.0
chr1 462 470 LEG 20.0 2.7

我在使用中读到的:

import pandas as pd 

df = pd.read_table(File)

数据框包含多列,其中一列是“Genes”。该列可以包含可变数量的条目。我想通过 FunctionsWithGenes 字典中的“Function”键分割数据框。到目前为止我已经:

df = df[df["Gene"].isin(FunctionsWithGenes.keys())] # to remove all rows with no matching entries

现在我需要根据基因功能以某种方式分割数据框。我想也许添加一个具有基因功能的新列,但不确定这是否有效,因为某些基因可以具有多个功能。

最佳答案

我对你的最后一行代码有点困惑:

 df = df[df["Gene"].isin(FunctionsWithGenes.keys())]

因为 FunctionsWithGenes 的键是实际函数(Emotions 等...),但基因列具有值。生成的 DataFrame 将始终为空。

如果我理解正确的话,你想将表分开,以便属于一个函数的所有基因都在一个表中,如果是这样的话,你可以使用简单的字典理解,我设置了一些类似的变量给你的:

>>> for function, genes in FunctionsWithGenes.iteritems():
... print function, genes
...
Walking ['LEG', 'MUSCLE', 'TENDON', 'BLOOD']
Singing ['VOCAL', 'NECK', 'BLOOD', 'HAPPY']
Emotions ['HAPPY', 'SAD', 'GOOFY', 'SILLY']
>>> df
Gene Value
0 HAPPY 3.40
1 SAD 4.30
2 LEG 5.55

然后我像这样分割DataFrame:

>>> FunctionsWithDf = {function:df[df['Gene'].isin(genes)]
... for function, genes in FunctionsWithGenes.iteritems()}

现在 FunctionsWithDf 是一个字典,它将 Function 映射到 DataFrame,其中 Gene 列的所有行都在FunctionsWithGenes[Function]

的值

例如:

>>> FunctionsWithDf['Emotions']
Gene Value
0 HAPPY 3.4
1 SAD 4.3
>>> FunctionsWithDf['Singing']
Gene Value
0 HAPPY 3.4

关于python - Pandas:基于字典分割和编辑文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26003662/

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