0

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!

6
  • What error do you get? Commented Sep 15, 2017 at 0:05
  • Why do you want to do this? This array will not have many of nice numpy.array properties. Commented Sep 15, 2017 at 0:07
  • Do not get error. My result would be [1,2,3,4,5] Commented Sep 15, 2017 at 0:08
  • I have two lists which I need to save them in a csv file. they do not have the same properties. Commented Sep 15, 2017 at 0:09
  • 1
    Normally a csv file has the same number of columns per line. How do you propose to do that with these 2 lists? Have you considered writing the lists individually to a file? Or with the csv module? Don't force them into an array if you don't need to. Commented Sep 15, 2017 at 0:59

2 Answers 2

1

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Could you show the repr of c - to see type and dtype?
1

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.]])

Comments

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.