I want to be able to convert an existing 2D array to a 1D array of arrays. The only way I can find is to use something like:
my_2d_array = np.random.random((5, 3))
my_converted_array = np.zeros(len(my_2d_array), dtype='O')
for i, row in enumerate(my_converted_array):
my_converted_array[i] = row
Is there a faster/cleaner method of doing this?
If the inner arrays have different shapes it is possible, for example:
my_1d_array = np.array([
np.array([0, 1], dtype=np.float),
np.array([2], dtype=np.float)
], dtype='O')
assert my_array.shape == (2,)
But if the arrays are the same length numpy automatically makes it a 2D array:
my_2d_array = np.array([
np.array([0, 1], dtype=np.float),
np.array([2, 3], dtype=np.float)
], dtype='O')
assert my_array.shape == (2, 2)
EDIT: To clarify for some answers, I can't use flatten
, reshape
or ravel
as they would maintain the same number of elements. Instead I want to go from a a 2D array with shape (N, M)
to a 1D array with shape (N,)
of objects (1D arrays), which each have shape (M,)
.