Python在数据帧中编码基因组数据

2024-09-26 20:51:55 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在尝试编码一个基因组,作为字符串存储在从CSV读取的数据帧中

现在我正在寻找将数据框中“Genome”列下的每个字符串拆分为它的碱基对列表,即从('acgt…')到('a','c','g','t'),然后将每个碱基对分别转换为浮点(0.25,0.50,0.75,1.00)

我想我正在寻找一个split函数来将每个字符串拆分为字符,但似乎没有一个函数能够处理数据帧中的数据,即使使用.tostring转换为字符串

以下是我最近的代码:

import re
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder


def string_to_array(my_string):
    my_string = my_string.lower()
    my_string = re.sub('[^acgt]', 'z', my_string)
    my_array = np.array(list(my_string))
    return my_array

label_encoder = LabelEncoder()
label_encoder.fit(np.array(['a','g','c','t','z']))

def ordinal_encoder(my_array):
    integer_encoded = label_encoder.transform(my_array)
    float_encoded = integer_encoded.astype(float)
    float_encoded[float_encoded == 0] = 0.25  # A
    float_encoded[float_encoded == 1] = 0.50  # C
    float_encoded[float_encoded == 2] = 0.75  # G
    float_encoded[float_encoded == 3] = 1.00  # T
    float_encoded[float_encoded == 4] = 0.00  # anything else, z
    return float_encoded



dfpath = 'C:\\Users\\CAAVR\\Desktop\\Ison.csv'
dataframe = pd.read_csv(dfpath)

df = ordinal_encoder(string_to_array(dataframe[['Genome']].values.tostring()))
print(df)

我试着做我自己的函数,但我不知道它们是如何工作的。我所做的一切都表明,当数据位于numpy数组中时,无法处理数据,并且无法将数据转换为其他类型

谢谢你的提示

编辑:这是数据框的打印-

 Antibiotic  ...                                             Genome
0       isoniazid  ...  ccctgacacatcacggcgcctgaccgacgagcagaagatccagctc...
1       isoniazid  ...  gggggtgctggcggggccggcgccgataaccccaccggcatcggcg...
2       isoniazid  ...  aatcacaccccgcgcgattgctagcatcctcggacacactgcacgc...
3       isoniazid  ...  gttgttgttgccgagattcgcaatgcccaggttgttgttgccgaga...
4       isoniazid  ...  ttgaccgatgaccccggttcaggcttcaccacagtgtggaacgcgg...

有5列“基因组”在列表中排名第五,我不知道为什么是1.head()将不起作用,2。为什么print()没有给我所有的列


Tags: 数据函数字符串import基因组encoderstringgenome
1条回答
网友
1楼 · 发布于 2024-09-26 20:51:55

我认为LabelEncoder不是你想要的。这是一个简单的转换,我建议直接进行。从查找您的碱基对映射开始:

lookup = {
  'a': 0.25,
  'g': 0.50,
  'c': 0.75,
  't': 1.00
  # z: 0.00
}

然后将查找应用于“Genome”列的值。values属性将以ndarray的形式返回结果数据帧

dataframe['Genome'].apply(lambda bps: pd.Series([lookup[bp] if bp in lookup else 0.0 for bp in bps.lower()])).values

相关问题 更多 >

    热门问题