How to change dtype ndarray to custom in numpy?

I made dtype which:

mytype = np.dtype([('a',np.uint8), ('b',np.uint8), ('c',np.uint8)]) 

so that the array uses this type of dtype:

 test1 = np.zeros(3, dtype=mytype) 

test1:

 array([(0, 0, 0), (0, 0, 0), (0, 0, 0)], dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')]) 

Now I have test2:

 test2 = np.array([[1,2,3], [4,5,6], [7,8,9]]) 

When I use test2.astype(mytype) , the result is not what I want to be:

 array([[(1, 1, 1), (2, 2, 2), (3, 3, 3)], [(4, 4, 4), (5, 5, 5), (6, 6, 6)], [(7, 7, 7), (8, 8, 8), (9, 9, 9)]], dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')]) 

I want the result to be:

 array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')]) 

Is there any way? Thanks.

+4
source share
2 answers

You can use the fromarrays method for numpy.core.records (see documentation ):

 np.rec.fromarrays(test2.T, mytype) Out[13]: rec.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')]) 

The array must first be converted because the functions treat the rows of the array as columns of a structured array in the output. See also this question: Converting a 2D numpy array to a structured array

+5
source

Since all fields are of the same type, you can also use:

 >>> test2.astype(np.uint8).view(mytype).squeeze(axis=-1) array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype=[('a', 'u1'), ('b', 'u1'), ('c', 'u1')]) 

Compression is necessary because test2 is 2d, but you need a 1d result

0
source

All Articles