mehmet
mehmet

Reputation: 45

Add some np arrays as new columns to my data

I want to add some (N x 1) np.arrays, as new columns to another np.array (N x M)

I have tried many things (append, transposing, hstack etc) but for some reason I cannot make it work.

For example:

a=[[1,2,3],[4,5,6], [7,8,9], [10,11,12]]
b=[100,200,300,400]
c=[100,200,300,400]
d=[100,200,300,400]

I want the result to be like this:

1,2,3,100,100,100
4,5,6,200,200,200
7,8,9,300,300,300
10,11,12,400,400,400

Upvotes: 0

Views: 42

Answers (2)

hpaulj
hpaulj

Reputation: 231385

Just concatenate them on the last axis:

In [329]: a=np.array([[1,2,3],[4,5,6], [7,8,9], [10,11,12]]) 
     ...: b=np.array([[100,200,300,400]]).T         # transpose a (1,4)
     ...: c=np.array([100,200,300,400])[:,None]     # add a dimension
     ...: d=np.array([[100],[200],[300],[400]])     # list of lists 

In [330]: np.concatenate([a,b,c,d], axis=-1)                                    
Out[330]: 
array([[  1,   2,   3, 100, 100, 100],
       [  4,   5,   6, 200, 200, 200],
       [  7,   8,   9, 300, 300, 300],
       [ 10,  11,  12, 400, 400, 400]])

Checking the shapes:

In [331]: [i.shape for i in [a,b,c,d]]                                          
Out[331]: [(4, 3), (4, 1), (4, 1), (4, 1)]

But the b that you show, np.array([100,200,300,400]) is (4,) shaped, not (4,1). So it requires an array reshape, such as that provided by column_stack.

Upvotes: 0

Nathaniel
Nathaniel

Reputation: 3290

You can use np.c_ to combine the data by columns:

a = [[1,2,3],[4,5,6], [7,8,9], [10,11,12]]
b = [100,200,300,400]
c = [100,200,300,400]
d = [100,200,300,400]

np.c_[a, b, c, d]
array([[  1,   2,   3, 100, 100, 100],
       [  4,   5,   6, 200, 200, 200],
       [  7,   8,   9, 300, 300, 300],
       [ 10,  11,  12, 400, 400, 400]])

You can also use ``column_stack'' to get the same result:

np.column_stack([a, b, c, d])
array([[  1,   2,   3, 100, 100, 100],
       [  4,   5,   6, 200, 200, 200],
       [  7,   8,   9, 300, 300, 300],
       [ 10,  11,  12, 400, 400, 400]])

Thanks to josemz for the more concise version.

Upvotes: 3

Related Questions