Minh-Long Luu
Minh-Long Luu

Reputation: 2731

Numpy: flatten multiple arrays of different shape from a dict

I have a dict containing np.array of different shapes:

d = {
   "a" : np.array([1, 2, 3]), # shape (3,)
   "b" : np.array([4]), # shape (1,)
   "c" : np.array([[5, 6, 7], [8, 9, 10]]) # shape (2, 3)
}

Now I want to append them to form a vector, like this:

output = np.array([1,2,3,4,5,6,7,8,9,10])

How can I do that?

Upvotes: 2

Views: 432

Answers (2)

Anurag Dabas
Anurag Dabas

Reputation: 24324

import numpy as np
from pandas.core.common import flatten

With pandas:

array=np.array(list(flatten(d.values())))

With numpy:

array=np.hstack([arr.ravel() for arr in d.values()])

Upvotes: 2

Brad Day
Brad Day

Reputation: 400

This is one way to do it. Probably not the most efficient since new_arr changes shape on every iteration. You could probably iterate the dictionary once to determine the number of elements and create a new array with the correct size but that is more involved.

import numpy as np
d = {
   "a" : np.array([1, 2, 3]), # shape (3,)
   "b" : np.array([4]), # shape (1,)
   "c" : np.array([[5, 6, 7], [8, 9, 10]]) # shape (2, 3)
}
# %%
new_arr = np.array([])
for arr in d.values():
    new_arr = np.append(new_arr, arr.flatten(),axis=0)

Upvotes: 0

Related Questions