首页 > 解决方案 > Python - 在数据框中编码基因组数据

问题描述

您好我正在尝试编码一个基因组,该基因组存储为从 CSV 读取的数据帧内的字符串。

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

我以为我正在寻找一个拆分函数来将每个字符串拆分为字符,但即使使用转换为字符串,似乎也没有一个可以处理数据框中的数据.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 列“基因组”是列表中的第 5 列我不知道为什么 1..head()不起作用 2. 为什么print()不给我所有列...

标签: pythonpandasdataframeencoding

解决方案


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

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

然后将查找应用于“基因组”列的值。该values属性将结果数据框作为ndarray.

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

推荐阅读