NumPy:以编程方式修改结构化数组的数据类型
我有一个结构化数组,例如:
import numpy as np
orig_type = np.dtype([('Col1', '<u4'), ('Col2', '<i4'), ('Col3', '<f8')])
sa = np.empty(4, dtype=orig_type)
其中 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')])
现在,在我的程序中,我以某种方式决定需要将“Col2”的数据类型更改为字符串。我如何修改dtype
来做到这一点,例如非编程方式:
new_type = np.dtype([('Col1', '<u4'), ('Col2', '|S10'), ('Col3', '<f8')])
new_sa = sa.astype(new_type)
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')])
如何以编程方式修改orig_type 到
new_type
? (不用担心长度|S10
)。有没有一种“简单”的方法,或者我是否需要一个 for 循环来构造一个新的 dtype 构造函数对象?
I have a structured array, for example:
import numpy as np
orig_type = np.dtype([('Col1', '<u4'), ('Col2', '<i4'), ('Col3', '<f8')])
sa = np.empty(4, dtype=orig_type)
where sa
looks like (random data):
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')])
Now, in my program, I somehow decide that I need to change the data type of 'Col2' to a string. How can I modify the dtype
to do this, for example the non-programmatic way:
new_type = np.dtype([('Col1', '<u4'), ('Col2', '|S10'), ('Col3', '<f8')])
new_sa = sa.astype(new_type)
where new_sa
now looks like, which is great:
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')])
How do I programmatically modify orig_type
to new_type
? (don't worry about the length |S10
). Is there an "easy" way, or do I need a for-loop to construct a new dtype
constructor object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有捷径。您只需根据自己的喜好构造新的数据类型并使用
.astype()
即可。There is no shortcut. You would just construct the new dtype however you like and use
.astype()
.如果您的问题实际上旨在如何从旧对象构造新的 dtype 对象,那么这可能就是您正在寻找的内容:
If your question actually aims at how to construct the new
dtype
object from the old one, this may be what you are looking for: