Inconsistent behaviour with numpy broadcasting while creating array of array

Viewed 57

If I'm trying to execute :

a = np.ones((1, 2))
b = np.ones((1, 3))

np.array([a, b], dtype=np.ndarray)

I get the following error :

ValueError: could not broadcast input array from shape (2,) into shape (1,)

But I'm would like to get :

array([array([[1., 1.]]), array([[1., 1., 1.]])], dtype=object)

But if I'm executing this :

a = np.ones((1, 2))
b = np.ones((2, 4))

np.array([a, b], dtype=np.ndarray)

I get the expected results :

array([array([[1., 1.]]), array([[1., 1., 1.],
                                 [1., 1., 1.]])], dtype=object)

Running on :

numpy==1.21.2 python==3.7.11

1 Answers

Based on @hpaulh comments, this works:

import numpy as np


a = np.ones((1, 2))
b = np.ones((1, 3))

test = np.empty((2,), dtype=np.ndarray)

test[0] = a
test[1] = b

returns

array([array([[1., 1.]]), array([[1., 1., 1.]])], dtype=object)
Related