gpt4 book ai didi

python-3.x - 连接两个数组作为坐标对

转载 作者:行者123 更新时间:2023-12-04 13:34:08 26 4
gpt4 key购买 nike

我有两个 numpy 数组,我需要将它们组合在一个二维数组中:每一行必须是一对坐标。例如,如果 numpy 数组是:

[1 2 3]
[a b c]
那么我的目标是:
[[1 a]
[1 b]
[1 c]
[2 a]
[2 b]
[2 c]
[3 a]
[3 b]
[3 c]]
我试过这个:
    import numpy as np

x1_start, x1_stop, x1_step = 88.5, 91.5, 0.2
x2_start, x2_stop, x2_step = 82, 90, 0.5

x1 = np.arange(x1_start, x1_stop, x1_step)
x2 = np.arange(x2_start, x2_stop, x2_step)

x1x2 = np.array([])

for k in range(len(x1)):
for h in range(len(x2)):
list = [x1[k], x2[h]]
np.append(x1x2, list ,0)
但结果是一个空的 numpy 数组。或者,我试过这个:
x1x2 = []

for k in range(len(x1)):
for h in range(len(x2)):
x1x2.append([x1[k],x2[h]])

print(type(x1x2))
np.asarray(x1x2)
print(type(x1x2))
该列表包含正确的数字,但是当我打印它的类型时,它原来是一个列表,无论是在 np.array 转换之前还是之后。

最佳答案

一种方式 meshgrid

x = np.array([1,2,3])
y = np.array([4,5,6])
np.array(np.meshgrid(x, y)).T.reshape(-1, 2)
会导致
array([[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2, 5],
[2, 6],
[3, 4],
[3, 5],
[3, 6]])
meshgrid配对所有可能的组合,转置将它们放在一起,然后根据需要进行 reshape 。

关于python-3.x - 连接两个数组作为坐标对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63226973/

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