gpt4 book ai didi

python - 将两个不同 dtype 的 numpy 数组组合成一个结构化数组

转载 作者:行者123 更新时间:2023-12-01 03:02:22 24 4
gpt4 key购买 nike

我有一个 numpy float 数组和一个长度相同的 int 数组。我想连接它们,以便输出具有 composite dtype (float, int) . column_stack将它们放在一起只会产生 float64大批:

import numpy

a = numpy.random.rand(5)
b = numpy.random.randint(0, 100, 5)

ab = numpy.column_stack([a, b])
print(ab.dtype)
float64

任何提示?

最佳答案

创建一个“空白”数组:

In [391]: dt = np.dtype('f,i')                                                                 
In [392]: arr = np.zeros(5, dtype=dt)
In [393]: arr
Out[393]:
array([(0., 0), (0., 0), (0., 0), (0., 0), (0., 0)],
dtype=[('f0', '<f4'), ('f1', '<i4')])

填充:
In [394]: arr['f0']=np.random.rand(5)                                                          
In [396]: arr['f1']=np.random.randint(0,100,5)
In [397]: arr
Out[397]:
array([(0.40140057, 75), (0.93731374, 99), (0.6226782 , 48),
(0.01068745, 68), (0.19197434, 53)],
dtype=[('f0', '<f4'), ('f1', '<i4')])

也可以使用 recfunctions,但是了解(和理解)这种基本方法是很好的。

关于python - 将两个不同 dtype 的 numpy 数组组合成一个结构化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60270090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com