Rani
Rani

Reputation: 503

Concatenating arrays of different shapes

Given numpy arrays of different dimensions, I want to concatenate them. Apparently this is quite a common problem but the answers I found didn't seem to match my problem.

After trying several different approaches on a little example I still can't make it work. I've already looked into Concat two arrays of different dimensions numpy and How to unnest a nested list [duplicate]. I also tried appending and flattening it.

import numpy as np

a = np.arange(9)
a = a.reshape((3,3))
b = []
b.append(a[0,:])
b.append(a[1,1:2])
b.append(a[2,2])
b = np.asarray(b).flatten()
print(b) # [array([0, 1, 2]) array([4]) 8]

In summary I always get some error messages stating that the dimensions don't match or something similar.

Upvotes: 1

Views: 1723

Answers (1)

hpaulj
hpaulj

Reputation: 231385

So b is a list - with a (3,) and (1,) arrays, and a scalar (0d, ()):

In [76]: a=np.arange(9).reshape(3,3)                                            
In [77]: b = [a[0,:], a[1,1:2],a[2,2]]                                          
In [78]: b                                                                      
Out[78]: [array([0, 1, 2]), array([4]), 8]

But what combination do you want?

If the last item was an array (or list), we can concatenate:

In [79]: b = [a[0,:], a[1,1:2],[a[2,2]]]                                        
In [80]: b                                                                      
Out[80]: [array([0, 1, 2]), array([4]), [8]]
In [81]: np.concatenate(b)                                                      
Out[81]: array([0, 1, 2, 4, 8])

hstack is a cover for concatenate that makes sure all elements are at least 1d:

In [82]: b = [a[0,:], a[1,1:2],a[2,2]]                                          
In [83]: np.hstack(b)                                                           
Out[83]: array([0, 1, 2, 4, 8])

Upvotes: 2

Related Questions