Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: concatenate arrays stored in a dictionary

Tags:

python

numpy

I have a large dictionary which stores following arrays:

Store = dict()
Store['A'] = A #size 500x30
Store['B'] = B #size 500x20

I am having only A and B for illustration. In my current real life situation I have about 500 keys and values in the dictionary I am using.

I want to concatenate the arrays in an elegant way to get an array C.

For illustration this is what I aim to achieve:

A = np.random.normal( 0, 1, ( 500, 20 ) )
B = np.random.normal( 0, 1, ( 500, 30 ) )
C = np.concatenate((A,B),1)
like image 540
Zanam Avatar asked Dec 10 '22 18:12

Zanam


1 Answers

If the order does not matter, pass the values of your dictionary to numpy.concatenate:

>>> store = {'A':np.array([1,2,3]), 'B':np.array([3,4,5])}
>>> np.concatenate(store.values(),1)
array([1, 2, 3, 3, 4, 5])

If the order does matter, you can use

np.concatenate([v for k,v in sorted(store.items(), key=...)], 1)

Pass in any key function you like, or just leave the key argument out if you want to sort lexicographically. Sadly, concatenate does not seem to take a generator object.

like image 72
timgeb Avatar answered Dec 30 '22 22:12

timgeb