mimou
mimou

Reputation: 59

concatinate numpy matrices to get an array with dimension 3

I want to concatenate numpy matrices that have different shapes in order to get an array with dimension=3. example :

A= [[2 1 3 4]
    [2 4 0 6]
    [9 5 7 4]]
B= [[7 2 8 4]
    [8 6 8 6]]

and result what I need should be like that:

C=[[[2 1 3 4]
    [2 4 0 6]
    [9 5 7 4]]
   [[7 2 8 4]
    [8 6 8 6]]]

Thanks for help

Upvotes: 0

Views: 62

Answers (3)

hpaulj
hpaulj

Reputation: 231355

Because A and B have different sizes (# of rows), the best you can do make an array of shape (2,) and dtype object. Or at least that's what a simple construction gives you:

In [9]: np.array([A,B])
Out[9]: 
array([array([[2, 1, 3, 4],
       [2, 4, 0, 6],
       [9, 5, 7, 4]]),
       array([[7, 2, 8, 4],
       [8, 6, 8, 6]])], dtype=object)

But constructing an array like this doesn't help much. Just use the list [A,B].

np.vstack([A,B]) produces a (5,4) array.

np.array([A[:2,:],B]) gives a (2,2,4) array. Or you could pad B so they are both (3,4).

So one way or other you need to redefine your problem.

Upvotes: 0

eickenberg
eickenberg

Reputation: 14377

You can only convert to a 3D np.ndarray in a useful manner if A.shape == B.shape. In that case all you need to do is e.g. C = np.array([A, B]).

import numpy as np
A = np.array([[2, 1, 3, 4],
              [9, 5, 7, 4]])
B = np.array([[7, 2, 8, 4],
              [8, 6, 8, 6]])

C = np.array([A, B])
print C

Upvotes: 0

shx2
shx2

Reputation: 64288

If I understand your question correctly, a 3dim numpy array is probably not the way to represent your data, because there's no definitive shape.

A 3dim numpy array should have a shape of the form N1 x N2 x N3, whereas in your case each "2dim row" has a different shape.

Alternatives would be to keep your data in lists (or a list of arrays), or to use masked arrays, if that happens to be reasonable in you case.

Upvotes: 1

Related Questions