Sum Elements In A Row (Python/Numpy)
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 readi
Solution 1:
You're over-complicating it. Instead try:
np.sum(array,axis=1).tolist()
this should return a list which contain the sum of all rows
ex:
import numpy as np
array = np.array([range(10),range(10),range(10),range(10)])
sum_ = np.sum(array,axis=1).tolist()
print sum_
print type(sum_)
>> [45, 45, 45, 45]
>> <type 'list'>
Solution 2:
Okay. Figured out the answer.
@wajid Farhani was close, but it wasn't working in my case.
His command for np.sum works, but I had to perform some indexing so I can ignore index 0 of every row. My issue was that I thought indexing 2D array was done by array[x][y], when it's array[x,y].
Fixed 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))
print("number of rows:", len(r))
print("number of cols:", len(r[0]))
print("num1s before:",num1s)
array = numpy.array(r,dtype=int)
s = numpy.sum(array[0:len(array),1:len(array[0])],axis=1).tolist()
print("num1s after :",s)
Correct output:
num1s before: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
num1s after : [1, 4, 4, 4, 4, 5, 5, 3, 4, 5, 5, 3, 4, 3, 3, 3]
Post a Comment for "Sum Elements In A Row (Python/Numpy)"