Working on a project that gives us free reign on what to use. So I decided I'd learn python for it.
To make this short, I want sum all the elements in a "row" of a matrix I'm reading in.
This is what my 2D array looks like after I read in my table from my text file.
['0000' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '0' '1']
['0001' '0' '1' '0' '1' '0' '0' '0' '0' '1' '0' '0' '0' '0' '1']
['0010' '0' '1' '0' '1' '0' '0' '0' '0' '1' '0' '0' '0' '0' '1']
['0011' '0' '1' '0' '1' '0' '0' '0' '0' '1' '0' '0' '0' '0' '1']
['0100' '0' '0' '0' '0' '0' '1' '0' '1' '0' '0' '1' '0' '0' '1']
['0101' '0' '0' '1' '0' '0' '0' '1' '0' '0' '1' '0' '1' '1' '0']
['0110' '0' '0' '1' '0' '1' '0' '0' '0' '0' '1' '0' '1' '1' '0']
['0111' '0' '0' '1' '0' '0' '0' '0' '0' '0' '1' '0' '0' '1' '0']
['1000' '0' '0' '0' '0' '0' '1' '0' '1' '0' '0' '1' '0' '0' '1']
['1001' '1' '0' '0' '0' '0' '0' '1' '0' '0' '1' '0' '1' '1' '0']
['1010' '1' '0' '0' '0' '1' '0' '0' '0' '0' '1' '0' '1' '1' '0']
['1011' '1' '0' '0' '0' '0' '0' '0' '0' '0' '1' '0' '0' '1' '0']
['1100' '0' '0' '0' '0' '0' '1' '0' '1' '0' '0' '1' '0' '0' '1']
['1101' '0' '0' '0' '0' '0' '0' '1' '0' '0' '0' '0' '1' '1' '0']
['1110' '0' '0' '0' '0' '1' '0' '0' '0' '0' '0' '0' '1' '1' '0']
['1111' '0' '0' '0' '0' '0' '0' '0' '0' '0' '1' '0' '1' '1' '0']
I want to sum all elements of each row excluding index 0 (the 4 digit numbers). And then store those sums in a list.
This is what my list of sums should look like:
[1, 4, 4, 4, 4, 4, 5, 5, 3,.......,3] (Imagine it was all filled with the right sums)
However, this is what my code outputs:
number of rows: 16
number of cols: 15
num1s before: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
num1s after : [3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 7, 9, 7]
I'm not sure what the error is, but I think it has to do with string/int conversion. Since my table is in strings, but I convert it to ints for summing. Debugging it shows the correct results, so I'm not sure where the error is.
Here is my code:
import numpy
print ("Reading..")
txtfile = open("test1.txt", "r")
print(txtfile.readline())
txtfile.close()
r= numpy.genfromtxt('test1.txt',dtype=str,skiprows=1)
for x in range (0,len(r)):
print(r[x])
allTested = [0] * (len(r[0]) - 1)
num1s = [0] * (len(r[0]) - 1)
print("number of rows:", len(r))
print("number of cols:", len(r[0]))
print("num1s before:",num1s)
for x in range (0,len(r)):
for y in range(1,len(r[0])):
num1s[y-1] += int(r[x][y])
print("num1s after :",num1s)