x 和 y 数组点的笛卡尔积转化为单个二维点数组 [英] Cartesian product of x and y array points into single array of 2D points

查看:24
本文介绍了x 和 y 数组点的笛卡尔积转化为单个二维点数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 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 数组点的笛卡尔积转化为单个二维点数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆