Elham
Elham

Reputation: 867

merging two Numpy Array

I have a very simple question ! How can I merge two numpy array with increasing the dimension:

Suppose I have the following arrays :

a=[1,2]
b=[3,4,5]

I need this result :

c=[[1,2],[3,4,5]

However

np.concatenate((a,b),axis=0)

does not work !

Thanks!

Upvotes: 0

Views: 232

Answers (2)

hpaulj
hpaulj

Reputation: 231385

Put them together in a list:

In [269]: c = [a,b]
In [270]: c
Out[270]: [[1, 2], [3, 4, 5]]

Making an array from that doesn't work very well:

In [271]: np.array(c)
Out[271]: array([list([1, 2]), list([3, 4, 5])], dtype=object)

But if your goal is just to write the lists to a file, csv style, we can do:

In [272]: for row in c:
     ...:     line=''
     ...:     for x in row:
     ...:         line += '%5s'%x
     ...:     print(line)
     ...:     
    1    2
    3    4    5

For a file just substitute the file write for the print.

numpy has a nice savetxt but it requires a nice 2d array. That ragged 1d object dtype array does not work.

itertools.zip_longest can also be used to 'pad' the elements of c. But simply writing to the file is simplest.

Using zip_longest to pad the rows, and then using savetxt to write the csv. Note the 'blank' delimited 'cell':

In [321]: rows =list(zip(*zip_longest(*c,fillvalue='')))
In [322]: rows
Out[322]: [(1, 2, ''), (3, 4, 5)]
In [323]: np.savetxt('foo.txt',rows, fmt='%5s',delimiter=',')
In [324]: cat foo.txt
    1,    2,     
    3,    4,    5

with the proper padding, I can reload the csv (may need to fiddle with the fill value):

In [328]: np.genfromtxt('foo.txt',delimiter=',')
Out[328]: 
array([[  1.,   2.,  nan],
       [  3.,   4.,   5.]])

Upvotes: 1

sagunms
sagunms

Reputation: 8515

You can simply do the following to get the result you want.

c = [a,b]

Or

c = np.array([a,b])

Result:

[[1, 2], [3, 4, 5]]

Upvotes: 1

Related Questions