Solution for arbitrary number of dimensions:
As of now, all other answers fail for multi-dimensional cases, so I came up with a general function. It converts an object array (of arbitrary shape) of same-shape numpy arrays (of arbritrary dimensions) to a normal Numpy array:
def obj_array_to_type(arr, typ):
"""
Convert an object array of same-sized arrays to a normal 3D array
with dtype=typ. This is a workaround as numpy doesn't realize that
the object arrays are numpy arrays of the same legth, so just using
array.astype(typ) fails. Technically works if the items are numbers
and not arrays, but then `arr.astype(typ)` should be used.
"""
full_shape = (*arr.shape, *np.shape(arr.flat[0]))
return np.vstack(arr.flatten()).astype(typ).reshape(full_shape)
Explanation:
- First we expand the original dimensions of the object array with the dimensions of the very first item of the object array (
arr.flat[0]).
- We
flatten the array and then apply np.vstack on it, as other answers have shown.
- We apply the type, and then reshape the array to the full size.
As every function only modifies numpy's view on the array, the actual content is never copied/duplicated, so this is also fast on very huge arrays.
Example:
>>> # Just generate an object array of arrays
>>> a = np.empty((3,3), dtype=object)
>>> for i in range(9):
... a[i//3, i%3] = np.array([1,2,3,4])
...
>>> a
array([[array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 2, 3, 4])],
[array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 2, 3, 4])],
[array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 2, 3, 4])]],
dtype=object)
>>> # This will fail:
>>> a.astype(float)
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: setting an array element with a sequence.
>>> obj_array_to_type(a, float)
array([[[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.]],
[[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.]],
[[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.]]])