Numpy Stacking 1D Arrays in a Structured Array

I am running Numpy 1.6 in Python 2.7 and have several 1D arrays that I get from another module. I would like to take these arrays and pack them into a structured array so that I can index the original 1D arrays by name. I am having trouble figuring out how to get 1D arrays into a 2D array and get dtype to access the correct data. My MWE is as follows:

>>> import numpy as np >>> >>> x = np.random.randint(10,size=3) >>> y = np.random.randint(10,size=3) >>> z = np.random.randint(10,size=3) >>> x array([9, 4, 7]) >>> y array([5, 8, 0]) >>> z array([2, 3, 6]) >>> >>> w = np.array([x,y,z]) >>> w.dtype=[('x','i4'),('y','i4'),('z','i4')] >>> w array([[(9, 4, 7)], [(5, 8, 0)], [(2, 3, 6)]], dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')]) >>> w['x'] array([[9], [5], [2]]) >>> >>> u = np.vstack((x,y,z)) >>> u.dtype=[('x','i4'),('y','i4'),('z','i4')] >>> u array([[(9, 4, 7)], [(5, 8, 0)], [(2, 3, 6)]], dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')]) >>> u['x'] array([[9], [5], [2]]) >>> v = np.column_stack((x,y,z)) >>> v array([[(9, 4, 7), (5, 8, 0), (2, 3, 6)]], dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')]) >>> v.dtype=[('x','i4'),('y','i4'),('z','i4')] >>> v['x'] array([[9, 5, 2]]) 

As you can see, while my original x array contains [9,4,7] , I did not try to stack the arrays in any way, and then indexing with 'x' returns the original x array. Is there a way to do this, or am I not mistaken?

+4
source share
4 answers

One of the methods:

 wtype=np.dtype([('x',x.dtype),('y',y.dtype),('z',z.dtype)]) w=np.empty(len(x),dtype=wtype) w['x']=x w['y']=y w['z']=z 

Please note that the size of each number returned by randint depends on your platform, so instead of int32, i.e. i4, on my machine I have int64, which is "i8". This other method is more portable.

+6
source

You want to use np.column_stack :

 import numpy as np x = np.random.randint(10,size=3) y = np.random.randint(10,size=3) z = np.random.randint(10,size=3) w = np.column_stack((x, y, z)) w = w.ravel().view([('x', x.dtype), ('y', y.dtype), ('z', z.dtype)]) >>> w array([(5, 1, 8), (8, 4, 9), (4, 2, 6)], dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')]) >>> x array([5, 8, 4]) >>> y array([1, 4, 2]) >>> z array([8, 9, 6]) >>> w['x'] array([5, 8, 4]) >>> w['y'] array([1, 4, 2]) >>> w['z'] array([8, 9, 6]) 
+3
source

You might want to look into numpy record arrays for this use:

"Numpy provides powerful capabilities for creating arrays of structures or records. These arrays allow you to manipulate data using structures or structure fields."

Here's the documentation on record arrays: http://docs.scipy.org/doc/numpy/user/basics.rec.html

You can use variable names as field names.

+1
source

Use dictionary

 #!/usr/bin/env python import numpy w = {} for key in ('x', 'y', 'z'): w[key] = np.random.randint(10, size=3) print w 
0
source

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


All Articles