Home > Software design >  Formatting a dictionary with Python Numpy
Formatting a dictionary with Python Numpy

Time:11-08

How can I set the numpy array a into three list sets within the dictionary dictionary as one, two, three just like the expected output below?

import numpy as np 
set_names = np.array(['one', 'two', 'three'])
a = np.array([12,4,2,45,6,7,2,4,5,6,12,4])
dictionary = dict(zip(set_names, np.array_split(a, 3)))

Expected output:

{'one': array([12,  45,  2,  6]),
 'three': array([4, 6, 4, 12]),
 'two': array([2,  7,  5,  4])}

CodePudding user response:

Numpy has reshape method which, well, reshapes the given array:

Note: When you are reshaping a matrix, the output and input matrices must have equal total element. That's why you have to calculate the new shape, or you can use -1 as other value of reshape. It will calculate the value that fits.

You can reshape your array using:

a.reshape((3, -1))

Output:

[[12  4  2 45]
 [ 6  7  2  4]
 [ 5  6 12  4]]

But it's not what you are looking for. Let's make it 3 columns:

a.reshape((-1, 3))

Output:

[[12  4  2]
 [45  6  7]
 [ 2  4  5]
 [ 6 12  4]]

At first glance yoıu may not see it. But this is what you want. But as columns. Now we can get transpose of the matrix:

np.transpose(a.reshape((-1, 3)))

Output:

[[12 45  2  6]
 [ 4  6  4 12]
 [ 2  7  5  4]]

Last but not least do your dictionary thing:

import numpy as np

set_names = np.array(['one', 'two', 'three'])
a = np.array([12, 4, 2, 45, 6, 7, 2, 4, 5, 6, 12, 4])
dictionary = dict(zip(set_names, np.transpose(a.reshape((-1, 3)))))

Output:

{'one': array([12, 45,  2,  6]), 'two': array([ 4,  6,  4, 12]), 'three': array([2, 7, 5, 4])}
  • Related