Search code examples
pythonnumpygenfromtxt

Print summed arrays when importing files from numpy.genfromtxt


I have several files where the first column is text and the rest numbers like

first.txt

A 1 3 5 7 B 9 11 13 15

second.txt

A 0 4 6 8
B 10 12 14 16

which I import like

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

now basically, descr[] hold the string of the first column while a and b are arrays which I need now to sum up per column and print something like

summed result

A 1 7 11 15

B 19 23 27 31

I ve tried this

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

but I get

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


Solution

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