4

I have a 2D Numpy Array, and I want to apply a function to each of the rows and form a new column (the new first column) with the results. For example, let

M = np.array([[1,0,1], [0,0,1]])

and I want to apply the sum function on each row and get

array([[2,1,0,1], [1,0,0,1]])

So the first column is [2,1], the sum of the first row and the second row.

2
  • 1
    Make a 1 column array with the new values, and concatenate them. Commented Jul 22, 2021 at 23:30
  • 1
    np.column_stack((M.sum(1), M)) Commented Jul 22, 2021 at 23:31

2 Answers 2

5

You can generally append arrays to each other using np.concatenate when they have similar dimensionality. You can guarantee that sum will retain dimensionality regardless of axis using the keepdims argument:

np.concatenate((M.sum(axis=1, keepdims=True), M), axis=1)

This is equivalent to

np.concatenate((M.sum(1)[:, None], M), axis=1)
Sign up to request clarification or add additional context in comments.

Comments

1

Another similar way:

np.insert(M, 0, M.sum(1), 1)

output:

array([[2, 1, 0, 1],
       [1, 0, 0, 1]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.