从一维数组创建路径坐标的二维数组

时间:2019-05-04 16:26:11

标签: python numpy

我正在尝试从X Y Z位置的1d列表生成坐标数组。我使用的软件会按照给定优先级嵌套的每个列表进行迭代。 换句话说,如果我有x = [x0, x1]y = [y0, y1]z = [z0, z1],并且如果优先级为z> y> x,则对应的数组为:

x0 y0 z0
x0 y0 z1
x0 y1 z0
x0 y1 z1
x1 y0 z0
x1 y0 z1
x1 y1 z0
x1 y1 z1

我尝试过使用列表推导,但是输入是一维ndarrays而不是列表,这需要我将数据转换为列表,然后将结果转换回ndarray(在某些情况下,列表推导也可能缺乏灵活性)实施)。 numpy中是否有函数可以帮助生成这样的数组?

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
out = [[i, j, k] for i in x for j in y for k in z]
out = np.asarray(out)

输出

[[1, 4, 7],
 [1, 4, 8],
 [1, 4, 9],
 [1, 5, 7],
 [1, 5, 8],
 [1, 5, 9],
 [1, 6, 7],
 [1, 6, 8],
 [1, 6, 9],
 [2, 4, 7],
 [2, 4, 8],
 [2, 4, 9],
 [2, 5, 7],
 [2, 5, 8],
 [2, 5, 9],
 [2, 6, 7],
 [2, 6, 8],
 [2, 6, 9],
 [3, 4, 7],
 [3, 4, 8],
 [3, 4, 9],
 [3, 5, 7],
 [3, 5, 8],
 [3, 5, 9],
 [3, 6, 7],
 [3, 6, 8],
 [3, 6, 9]]

2 个答案:

答案 0 :(得分:0)

是的,您可以使用np.repeatnp.tile

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

out = np.zeros((len(x)**3, 3))
out[:, 0] = np.repeat(x, len(x)**2)
out[:, 1] = np.tile(np.repeat(y, len(x)), 3)
out[:, 2] = np.tile(z, len(x)**2)

输出:

[[1. 4. 7.]
 [1. 4. 8.]
 [1. 4. 9.]
 [1. 5. 7.]
 [1. 5. 8.]
 [1. 5. 9.]
 [1. 6. 7.]
 [1. 6. 8.]
 [1. 6. 9.]
 [2. 4. 7.]
 [2. 4. 8.]
 [2. 4. 9.]
 [2. 5. 7.]
 [2. 5. 8.]
 [2. 5. 9.]
 [2. 6. 7.]
 [2. 6. 8.]
 [2. 6. 9.]
 [3. 4. 7.]
 [3. 4. 8.]
 [3. 4. 9.]
 [3. 5. 7.]
 [3. 5. 8.]
 [3. 5. 9.]
 [3. 6. 7.]
 [3. 6. 8.]
 [3. 6. 9.]]

如果您先验地知道坐标是整数,则可以:

out = np.zeros((len(x)**3, 3), dtype=int)

答案 1 :(得分:0)

尝试一下。

np.array(np.meshgrid(x,y,z)).T.reshape(-1,3)

输出:

[[1 4 7]
 [1 5 7]
 [1 6 7]
 [2 4 7]
 [2 5 7]
 [2 6 7]
 [3 4 7]
 [3 5 7]
 [3 6 7]
 [1 4 8]
 [1 5 8]
 [1 6 8]
 [2 4 8]
 [2 5 8]
 [2 6 8]
 [3 4 8]
 [3 5 8]
 [3 6 8]
 [1 4 9]
 [1 5 9]
 [1 6 9]
 [2 4 9]
 [2 5 9]
 [2 6 9]
 [3 4 9]
 [3 5 9]
 [3 6 9]]