gpt4 book ai didi

python - 使用 itertools 创建 numpy 数组

转载 作者:太空狗 更新时间:2023-10-30 00:59:26 27 4
gpt4 key购买 nike

我想使用 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)

最佳答案

这里有几种用这些值生成数组的 numpy 方法

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]])

repeattile 对于这样的任务也很有用:

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 节省了适度的时间。

不久前,我探索了 itertoolsfromiter,并找到了一种使用 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]])

关于python - 使用 itertools 创建 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41492204/

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