首页 > 解决方案 > 从 numpy.genfromtxt 导入文件时打印求和数组

问题描述

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

第一个.txt

A 1 3 5 7 B 9 11 13 15

第二个.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 是数组,我现在需要对每列求和并打印类似

求和结果

一个 1 7 11 15

乙 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:具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()

标签: pythonnumpygenfromtxt

解决方案


I could not understand your question completely and your comment with total also did not help me much. Considering your total issue, you can do simply:

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])

It gives you the following result:

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

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

推荐阅读