x和y数组点的笛卡尔积变成2D点的单个数组 [英] Cartesian product of x and y array points into single array of 2D points
问题描述
我有两个numpy数组,它们定义了网格的x和y轴.例如:
I have two numpy arrays that define the x and y axes of a grid. For example:
x = numpy.array([1,2,3])
y = numpy.array([4,5])
我想生成这些数组的笛卡尔积以生成:
I'd like to generate the Cartesian product of these arrays to generate:
array([[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]])
这并不是一种非常低效的方式,因为我需要循环执行多次.我假设将它们转换为Python列表并使用itertools.product
并返回到numpy数组并不是最有效的形式.
In a way that's not terribly inefficient since I need to do this many times in a loop. I'm assuming that converting them to a Python list and using itertools.product
and back to a numpy array is not the most efficient form.
推荐答案
>>> numpy.transpose([numpy.tile(x, len(y)), numpy.repeat(y, len(x))])
array([[1, 4],
[2, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5]])
请参见使用numpy进行构建一个由两个数组的所有组合组成的数组,这是用于计算N个数组的笛卡尔积的一般解决方案.
See Using numpy to build an array of all combinations of two arrays for a general solution for computing the Cartesian product of N arrays.
这篇关于x和y数组点的笛卡尔积变成2D点的单个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!