我想使用itertools的各种函数来创建numpy数组。我可以很容易地提前计算产品中元素的数量,组合,排列等,因此分配空间不应该是一个问题。
EG
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]])