0

I have a 2-D numpy array X with shape (100, 4). I want to find the sum of each row of that array and store it inside a new numpy array x_new with shape (100,0). What I've done so far doesn't work. Any suggestions ?. Below is my approach.

x_new = np.empty([100,0])
for i in range(len(X)):
    array = np.append(x_new, sum(X[i]))
3
  • 2
    You can just use x_new = X.sum(axis=1) to get an array of size 100, and then reshape that to 100x1 if you really need it to be two-dimensional. Note that it is 100x1, not 100x0. Commented Oct 24, 2021 at 20:34
  • you can't put any values in a (100,0) shape array. See the 0? np.append is hard to use unless you really read its docs. Even then it is slower than list append. Commented Oct 24, 2021 at 21:02
  • As a very general rule of thumb, if you find yourself using a for loop with numpy arrays take a step back and take a different approach, non-looping approach to your problem. There's almost always a way with numpy's vectorization and broadcasting. Commented Oct 24, 2021 at 22:14

1 Answer 1

1

Using the sum method on a 2d array:

In [8]: x = np.arange(12).reshape(3,4)
In [9]: x
Out[9]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [10]: x.sum(axis=1)
Out[10]: array([ 6, 22, 38])
In [12]: x.sum(axis=1, keepdims=True)
Out[12]: 
array([[ 6],
       [22],
       [38]])
In [13]: _.shape
Out[13]: (3, 1)

reference: https://numpy.org/doc/stable/reference/generated/numpy.sum.html

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.