Unzip the dictionary of coordinates and values

I want to fill in the x , y and z values, where x is the x, y coordinates, y and z coordinates are the associated values โ€‹โ€‹for each coordinate, as defined by p . Here is how I do it:

 p = {(1,2): 10, (0,2):12, (2,0):11} k,z = np.array(list(zip(*p.items()))) x,y = np.array(list(zip(*k))) 

Is there an even more readable way? Perhaps there is something in numpy or scipy for this?

Why does z lead to array([10, 11, 12], dtype=object) and x a y does not include dtype=object ?

+5
source share
4 answers

What about a single layer?

 x, y, z = np.array([(x, y, z) for (x, y), z in p.items()]).T 

This makes it more clear where the values โ€‹โ€‹come from, without the unnecessary and unused k . In addition, you should not have a problem with dtype .

+6
source

Why dtype = object?

Consider the second line, now with one variable assignment:

 w = np.array(list(zip(*p.items()))) print(w) 

Here w becomes an array consisting of a string of tuples and a string int. Whenever such mixed types are involved, the generic data type object ( dtype ) is used. In your code, you have k, z = w , and so even if ints are stored in z , they retain their dtype ( object ).

Cleaner way

In one line we can do

 x, y, z = np.array([(x, y, z) for (x, y), z in p.items()]).T 

Here a list is created that stores the tuples of the form (x, y, z) . Then it is converted to a 2D NumPy array. Finally, this array (or matrix) is transposed ( .T ), and then x , y and z assigned. Transposition is necessary, because otherwise the rows of the matrix will be assigned x , y and z (try to leave .T and see the effect for yourself).

+2
source

If you used Pandas, the solution would be very readable:

 import pandas as pd data = pd.Series(p) #0 2 12 #1 2 10 #2 0 11 

If in the end you want numpy arrays:

 x = data.reset_index()['level_0'].values y = data.reset_index()['level_1'].values z = data.values 
+1
source

Since I like numpy, I would go with the following:

 keys = np.array(list(p.keys())) vals = np.matrix(list(p.values())) comb = np.concatenate((keys, vals.T), axis=1) x, y, z = comb.T 

How readable it is depends on how it is used for numpy.

There are two tricks. Firstly, the sorting of dictionary elements does not change if the dictionary has not changed, so we can call keys and values โ€‹โ€‹separately. The second way is to use np.matrix for the values, so transpose works because transferring a 1D array to numpy is nop.

+1
source

Source: https://habr.com/ru/post/1275306/


All Articles