gpt4 book ai didi

python - 如何从多个简单数组制作结构化数组

转载 作者:太空宇宙 更新时间:2023-11-04 10:57:58 24 4
gpt4 key购买 nike

import numpy as np

a=np.array([1,2,3,4,5,6,7,8,9])
b=np.array(["a","b","c","d","e","f","g","h","i"])
c=np.array([9,8,7,6,5,4,3,2,1])
datatype=np.dtype({
'names':['num','char','len'],
'formats':['i','S32','i']
})

d=np.array(zip(a,b,c),dtype=datatype)

上面的代码首先使用 zip() 创建一个列表,然后将其转换为结构化数组。它的效率很低,我想知道在 NumPy 中是否有任何内置函数可以做到这一点。

最佳答案

你不妨试试 numpy.rec.fromarrays

import numpy as np

a=np.array([1,2,3,4,5,6,7,8,9])
b=np.array(["a","b","c","d","e","f","g","h","i"])
c=np.array([9,8,7,6,5,4,3,2,1])

d = np.rec.fromarrays([a,b,c], formats=['i','S32','i'], names=['num','char','len'])

虽然计时不如使用 itertools

In [2]: %timeit d = np.rec.fromarrays([a,b,c], formats=['i','S32','i'], names=['num','char','len'])
10000 loops, best of 3: 86.5 us per loop

In [6]: import itertools

In [7]: %timeit np.fromiter(itertools.izip(a,b,c),dtype=datatype)
100000 loops, best of 3: 11.5 us per loop

关于python - 如何从多个简单数组制作结构化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8220689/

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