Salman Arshad
Salman Arshad

Reputation: 371

Sum two columns of a numpy array and add it as a third column of the array

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

Upvotes: 3

Views: 3700

Answers (1)

yatu
yatu

Reputation: 88305

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)

Upvotes: 5

Related Questions