【问题标题】:Add up the maximum value in each row of a matrix将矩阵每一行的最大值相加
【发布时间】:2015-06-01 17:40:56
【问题描述】:

我有以下代码

 #!/usr/bin/python
  import sys
  import re
  import string
  indexfile="ABC.txt"
  for line in open(indexfile,'rU').xreadlines():
    t = string.split(line,'\t')
    id = t[0];
    gene=t[1];
    pwmfile=id+'.txt'
    matrix_file = open(pwmfile, "rU")
    matrix = matrix_file.readlines()
    vals = [line[1:] for line in matrix[1:]]
    newpwmfile=id+'_formated.txt'
    ea=open(newpwmfile,'w')
    ea.seek(0)
    ea.write(">"+"ASTTCCTCTT "+gene)
    ea.writelines([line.lstrip('\t') for line in vals])
    ea.close()

以下是我得到的矩阵:

   >ABC/EFG
    0   0   1   0
    0.53333333333333    0   0.13333333333333    0.33333333333333
    0.2 0   0   0.8
    0.33333333333333    0   0   0.66666666666667
    0   1   0   0
    0   0.86666666666667    0.13333333333333    0
    0.33333333333333    0.066666666666667   0   0.6
    0   0   1   0

我想从每一行中找出最大值并将其除以 0.25 并对每一行求和。我还想得到一个字符串,它为字符串中的每个位置分配字母,例如最大值在该行的第三列中,然后是 G,对于第二行中的第一列,然后是 G 等并将它们连接起来,这样我在找到每行中的最高分数的同时得到一个类似 GAUUCCCG 的字符串。

【问题讨论】:

  • 你能用标准库读入你的文件吗?
  • @canyon289:很抱歉我没有找到你。

标签: python matrix


【解决方案1】:
import numpy as np

#make some fake data
m = np.random.random((8,4))

#get the sum you described
print 0.25*np.max(m, axis=1).sum()

#next, get the index the max value, for each row
xs = np.argmax(m, axis=1)
#use these as indexes into a string, e.g.
s = "GAUC"
print "".join(s[x] for x in xs)

【讨论】:

  • 感谢您的代码,但是当我将它插入到变量 'vals' 的原始代码中时,我收到错误:ValueError: 'axis' entry is out of bounds
  • 您需要将数据转换为二维数组。 (另外,请注意 xreadlines 不再需要遍历文件的行;这是默认行为。)尝试将 vals = [line[1:] for line in matrix[1:]] 更改为 vals = np.array([map(float,line.split()[1:]) for line in matrix[1:]])。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 2020-10-11
  • 2016-07-09
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
相关资源
最近更新 更多