首页 > 解决方案 > 填充一个空的多维矩阵

问题描述

我正在将fasta文件中的数据解析到字典中,然后遍历值以获得每个序列的汉明距离,我很难用汉明距离函数的输出填充一个空的多维数组。

from Bio import SeqIO
from scipy.spatial import distance
import pandas as pd
import numpy as np
from sklearn import manifold
import matplotlib.pyplot as plt

seq_dict = {rec.id : rec.seq for rec in SeqIO.parse("HW2.fas", "fasta")} #parsing fasta file into dic
ham_matrix = np.empty((0, 0 ), int)

for x in seq_dict.values():
    for y in seq_dict.values():
        distance.hamming(x, y)
    ham_matrix = np.append(ham_matrix, np.array([distance.hamming(x, y)]))

print (ham_matrix)

打印出来的矩阵应该有 120 行和 120 列的尺寸(字典的长度),但输出是

[0.29924242 0.3030303  0.3030303  0.30681818 0.30681818 0.29924242
 0.3030303  0.29924242 0.3030303  0.3030303  0.3030303  0.30681818
 0.3030303  0.3030303  0.3030303  0.29924242 0.32575758 0.32954545
 0.32575758 0.32575758 0.32954545 0.32954545 0.32575758 0.32954545
 0.32575758 0.32954545 0.33333333 0.32575758 0.32575758 0.3219697
 0.3219697  0.32575758 0.32954545 0.32954545 0.32954545 0.32954545
 0.32575758 0.32954545 0.32575758 0.3219697  0.31818182 0.32954545
 0.17424242 0.17424242 0.17045455 0.17045455 0.17424242 0.17045455
 0.17424242 0.1780303  0.17424242 0.17424242 0.17045455 0.17424242
 0.16666667 0.17045455 0.17045455 0.1780303  0.1780303  0.17424242
 0.17424242 0.17424242 0.18560606 0.18181818 0.18560606 0.18939394
 0.19318182 0.18939394 0.17424242 0.18181818 0.18181818 0.1780303
 0.18560606 0.1969697  0.17045455 0.18939394 0.1780303  0.18939394
 0.18560606 0.19318182 0.1780303  0.11742424 0.11363636 0.11742424
 0.11742424 0.08712121 0.10984848 0.10606061 0.10227273 0.08712121
 0.11742424 0.10984848 0.08712121 0.08333333 0.10984848 0.09090909
 0.09848485 0.10984848 0.07954545 0.10606061 0.08712121 0.10227273
 0.11363636 0.10227273 0.09090909 0.00757576 0.10227273 0.10606061
 0.10227273 0.10606061 0.00757576 0.09848485 0.09090909 0.00378788
 0.10984848 0.07954545 0.09469697 0.10606061 0.10606061 0.        ]

最好只创建一个空数组,用汉明距离函数的输出填充该空数组,然后在每次循环后将该数组作为一行附加到空矩阵中?

标签: pythonnumpy

解决方案


第一的:

您应该分配distance.hamming(x, y)返回给某个变量的值。否则你将徒劳地计算它,稍后在数组赋值中再次执行它。

第二:

我认为你的数组分配是相当偶然的,而且在错误的地方。

尝试这个:

for i, x in enumerate(seq_dict.values()):
    for j, y in enumerate(seq_dict.values()):
        ham_matrix[i, j] = distance.hamming(x, y)

未经测试的代码。如果还不能解决,请在下方评论。

顺便说一句:矩阵中看似随机的值是因为您使用了该np.empty()函数。它只是为数组分配所需的内存,并保留计算机之前保存的值。如果您使用np.zeros(),它将用零填充,这通常会清除问题。:)


推荐阅读