如何在numpy中将ndarray的dtype更改为自定义的?

Cli*_*pit 4 python numpy recarray

我做了一个dtype:

mytype = np.dtype([('a',np.uint8), ('b',np.uint8), ('c',np.uint8)])
Run Code Online (Sandbox Code Playgroud)

所以使用这个dtype的数组:

test1 = np.zeros(3, dtype=mytype)
Run Code Online (Sandbox Code Playgroud)

test1是:

array([(0, 0, 0), (0, 0, 0), (0, 0, 0)],
      dtype=[('a', '|u1'), ('b', '|u1'), ('c', '|u1')])
Run Code Online (Sandbox Code Playgroud)

现在我有test2:

test2 = np.array([[1,2,3], [4,5,6], [7,8,9]])
Run Code Online (Sandbox Code Playgroud)

当我使用时test2.astype(mytype),结果不是我想要的结果:

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')])
Run Code Online (Sandbox Code Playgroud)

我希望结果如下:

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

有什么办法吗?谢谢.

jor*_*ris 5

您可以使用fromarraysnumpy.core.records 的方法(参见文档):

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')])
Run Code Online (Sandbox Code Playgroud)

必须首先转置数组,因为函数将数组的行视为输出中结构化数组的列.另请参阅此问题:将2D numpy数组转换为结构化数组