[英]How do I create a compound dtype numpy array from existing individual vectors?
I am learning about dtypes
in numpy and I have the following doubt.我正在学习 numpy 中的
dtypes
,我有以下疑问。
I can define a compound type as follows:我可以如下定义复合类型:
myrecord = np.dtype([
('col1', 'u4'),
('col2', 'f8')
])
If I have two individual numpy arrays:如果我有两个单独的 numpy 数组:
a=np.array([1,2,3,4])
b=np.array([10.1,20.1,30.1,40.1])
How would I generate a third array c
of type my_record
?我将如何生成
my_record
类型的第三个数组c
?
This is what I tried, which it does not work but it might give an idea on what I am looking for:这是我尝试过的,它不起作用,但它可能会让我知道我在寻找什么:
c=np.array((a,b), dtype=myrecord)
This would be the expected output:这将是预期的输出:
array([(1, 10.1),
(2, 20.1),
(3, 30.1),
(4, 40.1),],
dtype=[('col1', '<u4'),('col2', '<f8')])
You're almost there!您快到了! You have to zip the
a
and b
columns together when creating c
:创建
c
时,您必须将a
和b
列压缩在一起:
import numpy as np
myrecord = np.dtype([
('col1', 'u4'),
('col2', 'f8')
])
a=np.array([1,2,3,4])
b=np.array([10.1,20.1,30.1,40.1])
c = np.array(list(zip(a, b)), dtype=myrecord)
Then when we view c
, you get the desired result:然后当我们查看
c
时,您会得到想要的结果:
>>>c
array([(1, 10.1), (2, 20.1), (3, 30.1), (4, 40.1)],
dtype=[('col1', '<u4'), ('col2', '<f8')])
Your example code is trying to create a tuple of arrays.您的示例代码正在尝试创建一个数组元组。 What you really wanted is an array of tuples.
你真正想要的是一个元组数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.