NumPy:以编程方式修改结构化数组的dtype

Mik*_*e T 6 python types numpy

我有一个结构化数组,例如:

import numpy as np
orig_type = np.dtype([('Col1', '<u4'), ('Col2', '<i4'), ('Col3', '<f8')])
sa = np.empty(4, dtype=orig_type)
Run Code Online (Sandbox Code Playgroud)

这里sa看起来像(随机数据):

array([(11772880L, 14527168, 1.079593371731406e-307),
       (14528064L, 21648608, 1.9202565460908188e-302),
       (21651072L, 21647712, 1.113579933986867e-305),
       (10374784L, 1918987381, 3.4871913811200906e-304)], 
      dtype=[('Col1', '<u4'), ('Col2', '<i4'), ('Col3', '<f8')])
Run Code Online (Sandbox Code Playgroud)

现在,在我的程序中,我以某种方式决定我需要将'Col2'的数据类型更改为字符串.如何修改dtype要执行此操作,例如非编程方式:

new_type = np.dtype([('Col1', '<u4'), ('Col2', '|S10'), ('Col3', '<f8')])
new_sa = sa.astype(new_type)
Run Code Online (Sandbox Code Playgroud)

这里new_sa现在看起来,这是伟大的:

array([(11772880L, '14527168', 1.079593371731406e-307),
       (14528064L, '21648608', 1.9202565460908188e-302),
       (21651072L, '21647712', 1.113579933986867e-305),
       (10374784L, '1918987381', 3.4871913811200906e-304)], 
      dtype=[('Col1', '<u4'), ('Col2', '|S10'), ('Col3', '<f8')])
Run Code Online (Sandbox Code Playgroud)

我如何orig_type以编程方式修改为new_type?(不要担心长度|S10).有一种"简单"的方式,还是我需要一个for循环来构造一个新的dtype构造函数对象?

Rob*_*ern 5

没有捷径.您只需构建新的dtype,但您喜欢并使用它.astype().


Sve*_*ach 4

如果您的问题实际上旨在如何dtype从旧对象构造新对象,那么这可能就是您正在寻找的内容:

orig_type = sa.dtype
descr = orig_type.descr
descr[1] = (descr[1][0], "|S10")
new_type = numpy.dtype(descr)
Run Code Online (Sandbox Code Playgroud)