odbhut.shei.chhele
odbhut.shei.chhele

Reputation: 6224

How to convert a 2d numpy array into a 1d numpy array by summing the values and not using for loop?

Is there a numpy function which can combine a 2d numpy array into a 1d numpy array. I want to do it without using a for loop.

Example:

[[1 0 0 0 0], [0 1 0 0 0]] => [1 1 0 0 0]

Upvotes: 0

Views: 857

Answers (1)

yacola
yacola

Reputation: 3013

Just use the ndarray method sum along row axis:

arr2d = np.array([[1, 3, 8, 2, 0], [0, 1, 0, 5, 1]])

arr1d = arr2d.sum(axis=0)

>>> array([1, 4, 8, 7, 1])

Upvotes: 1

Related Questions