使用迭代器创建NumPy数组 [英] Using itertools to create numpy array
本文介绍了使用迭代器创建NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用iterTools的各种函数来创建NumPy数组。我可以很容易地提前计算产品中元素的数量、组合、排列等,因此分配空间应该不是问题。
例如
coords = [[1,2,3],[4,5,6]]
iterable = itertools.product(*coords)
shape = (len(coords[0]), len(coords[1]))
arr = np.iterable_to_array(
iterable,
shape=shape,
dtype=np.float64,
count=shape[0]*shape[1]
) #not a real thing
answer = np.array([
[1,4],[1,5],[1,6],
[2,4],[2,5],[2,6],
[3,4],[3,5],[3,6]])
assert np.equal(arr, answer)
推荐答案
以下是使用这些值生成数组的几种简单方法
In [469]: coords = [[1,2,3],[4,5,6]]
In [470]: it = itertools.product(*coords)
In [471]: arr = np.array(list(it))
In [472]: arr
Out[472]:
array([[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2, 5],
[2, 6],
[3, 4],
[3, 5],
[3, 6]])
fromiter
将使用适当的结构化dtype
:
In [473]: it = itertools.product(*coords)
In [474]: arr = np.fromiter(it, dtype='i,i')
In [475]: arr
Out[475]:
array([(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5),
(3, 6)],
dtype=[('f0', '<i4'), ('f1', '<i4')])
但我们通常使用numpy
提供的工具来生成序列和网格。np.arange
随处可见。
meshgrid
被广泛使用。经过一些试错,我发现我可以转置它的输出,并产生相同的序列:
In [481]: np.transpose(np.meshgrid(coords[0], coords[1], indexing='ij'), (1,2,0)).reshape(-1,2)
Out[481]:
array([[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2, 5],
[2, 6],
[3, 4],
[3, 5],
[3, 6]])
repeat
和tile
对于这样的任务也很有用:
In [487]: np.column_stack((np.repeat(coords[0],3), np.tile(coords[1],3)))
Out[487]:
array([[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2, 5],
[2, 6],
[3, 4],
[3, 5],
[3, 6]])
我过去在fromiter
上做过一些计时。我的记忆是,它只比np.array
节省了少量时间。
不久前我研究了itertools
和fromiter
,找到了一种使用itertools.chain
convert itertools array into numpy array
In [499]: it = itertools.product(*coords)
In [500]: arr = np.fromiter(itertools.chain(*it),int).reshape(-1,2)
In [501]: arr
Out[501]:
array([[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2, 5],
[2, 6],
[3, 4],
[3, 5],
[3, 6]])
这篇关于使用迭代器创建NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文