我有一个numpy浮点数组和一个长度相同的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
有任何提示吗?
答案 0 :(得分:2)
创建一个“空白”数组:
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')])
也可以使用重新函数,但是很高兴知道(并理解)这种基本方法。