从 numpy.genfromtxt 导入文件时打印求和数组

Print summed arrays when importing files from numpy.genfromtxt

我有几个文件,其中第一列是文本,其余数字如

first.txt

A 1 3 5 7 B 9 11 13 15

second.txt

A 0 4 6 8
B 10 12 14 16

我喜欢

a=[] 
b=[]
descr=[]

descr.append( np.genfromtxt('first_file.txt', dtype=None,usecols=(0)))
for counter in range(1,5) :
    a.append( np.genfromtxt('first_file.txt', dtype=None,usecols=(counter+1)))
    b.append( np.genfromtxt('second_file.txt', dtype=None,usecols(counter+1)))

现在基本上,descr[] 保存第一列的字符串,而 a 和 b 是我现在需要对每列求和并打印类似

的数组

summed result

A 1 7 11 15

B 19 23 27 31

我试过这个

total = a+b

lines = ['  \t'.join([str(x[i]) if len(x) > i else ' ' for x in total]) for i in range(len(max(total)))]
for i in range(len(descr)):
    if descr[i] != '' :
        print '{}  {}'.format(descr[i], lines[i])

但我得到

lines = [' \t'.join([str(x[i]) if len(x) > i else ' ' for x in tot]) for i in range(len(max(tot)))] ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

你的一个错误是在表达式 max(total) 中,假设你想要数组的最大长度使用:

l = max(map(len, total))

然后,按照您的语法:

lines = ['  \t'.join([str(x[i]) if len(x) > i else ' ' for x in total]) for i in range(l)]

如果这没有给出预期的结果,请添加预期输出的样本

我无法完全理解您的问题,您对 total 的评论也对我没有太大帮助。考虑到你的总问题,你可以简单地做:

import numpy as np 
a = []
b = []

descr = np.genfromtxt('first.txt', dtype=None, usecols=(0))

for counter in range(1,5):
    temp = np.genfromtxt('first.txt', dtype=None,usecols=(counter))
    a.append(temp)
    temp = np.genfromtxt('second.txt', dtype=None,usecols=(counter))
    b.append(temp)

total = []
seq = []
seq.append(a)
seq.append(b)
total.append(np.sum(seq,axis=0))
print("Total: ")
print(total)

print("\nResult: ")
for i in range(len(descr)):
    if descr[i] != '' :
        print (descr[i], total[0][:,i])

它给你以下结果:

Total: 
[array([[ 1, 19],
       [ 7, 23],
       [11, 27],
       [15, 31]])]

Result: 
b'A' [ 1  7 11 15]
b'B' [19 23 27 31]