如何将 numpy 数组与循环合并



我正在尝试使用其他两个变量的数据实现一个数组

我的代码是这样的:

import numpy as np
x1 = [200,50,125,275,350]
x2 = [475,575,700,700,575]
#array = np.array([[200,475],[50,575],[125,700],[275,700],[350,575]])
array = np.array(
for j in range(5):
#for i in range(2):
[x1[i],x2[i]]
)

提前谢谢你

预期结果数组([[200,475], [50,575], [125,700], [275,700], [350,575]])

您可以使用zip然后转换为列表并使用numpy.asarray获取为数组也可以使用numpy.column_stack

import numpy as np
x1 = [200,50,125,275,350]
x2 = [475,575,700,700,575]
res = np.asarray(list(zip(x1,x2)))
res_2 = np.column_stack((x1,x2))
<小时 />
>>> res
array([[200, 475],
[ 50, 575],
[125, 700],
[275, 700],
[350, 575]])
>>> res_2
array([[200, 475],
[ 50, 575],
[125, 700],
[275, 700],
[350, 575]])

您可以通过串联来实现,但您也可以通过构建 2D 数组并转置来实现:

import numpy as np
x1 = [200,50,125,275,350]
x2 = [475,575,700,700,575]
a = np.array([x1,x2]).T
print(a)

输出:

[[200 475]
[ 50 575]
[125 700]
[275 700]
[350 575]]

您可以使用 numpy 的内置函数 - numpy.stack()

import numpy as np
x1 = [200,50,125,275,350]
x2 = [475,575,700,700,575]
arr = np.stack((x1, x2), axis=1)
print(arr)

输出:

[[200 475]
[ 50 575]
[125 700]
[275 700]
[350 575]]

最新更新