简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM