3

I have following numpy array

X = np.random.random_integers(100000000,size=(100000000,2))

now I want to dd both the columns of the array to generate the third column of the array. I am trying X[3] = X[0]+X[1] but its shape is (2,).

Example final array :

10    5    15
15    6    21

1 Answer 1

5

You could np.concatenate with the sum along the last axis. An additional axis must be added to the result of X.sum(1), as all arrays to be concatenated must have the same number of dimensions. This can be done either with None/np.newaxis:

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

3 Comments

what is the purpose of [:,None]
It adds an axis to X.sum(1), as all arrays to concatenate must have the same number of dimensions @salman
@SalmanArshad you can also use keepdims=True in sum, which removes the need for the extra broadcast

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.