How to create a structured array from several simple arrays

import numpy as np

a=np.array([1,2,3,4,5,6,7,8,9])
b=np.array(["a","b","c","d","e","f","g","h","i"])
c=np.array([9,8,7,6,5,4,3,2,1])
datatype=np.dtype({
 'names':['num','char','len'],
 'formats':['i','S32','i']
})

d=np.array(zip(a,b,c),dtype=datatype)

the above code uses zip () to first create a list and then convert it to a structured array. This is low efficiency, I want to know if there are built-in functions that can do this in NumPy.

+1
source share
2 answers

You can also try numpy.rec.fromarrays.

import numpy as np

a=np.array([1,2,3,4,5,6,7,8,9])
b=np.array(["a","b","c","d","e","f","g","h","i"])
c=np.array([9,8,7,6,5,4,3,2,1])

d = np.rec.fromarrays([a,b,c], formats=['i','S32','i'], names=['num','char','len'])

Although the timings are not as good as the use itertools.

In [2]: %timeit d = np.rec.fromarrays([a,b,c], formats=['i','S32','i'], names=['num','char','len'])
10000 loops, best of 3: 86.5 us per loop

In [6]: import itertools

In [7]: %timeit np.fromiter(itertools.izip(a,b,c),dtype=datatype)
100000 loops, best of 3: 11.5 us per loop
+2
source

zipcreates a list of tuples that can be memory intensive if arrays are large. You can use itertools.izipto save more memory:

import itertools
d=np.fromiter(itertools.izip(a,b,c),dtype=datatype)

For small arrays of length ~ 10:

In [68]: %timeit np.fromiter(itertools.izip(a,b,c),dtype=datatype)
100000 loops, best of 3: 15.8 us per loop

In [69]: %timeit np.array(zip(a,b,c),dtype=datatype)
10000 loops, best of 3: 20.8 us per loop

For arrays ~ 10,000 long:

In [72]: A=np.tile(a,1000)
In [74]: B=np.tile(b,1000)
In [75]: C=np.tile(c,1000)

In [83]: %timeit np.fromiter(itertools.izip(A,B,C),dtype=datatype)
100 loops, best of 3: 10.7 ms per loop

In [84]: %timeit np.array(zip(A,B,C),dtype=datatype)
100 loops, best of 3: 12.7 ms per loop

, np.fromiter , np.array.

+2

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


All Articles