gpt4 book ai didi

python - 如何使用列的值将 2 个 numpy ndarray 合并到 ndarray 上?

转载 作者:行者123 更新时间:2023-12-01 09:14:31 27 4
gpt4 key购买 nike

我有 2 个数组:

a = np.array([[1,2], [5,0], [6,4]])
b = np.array([[1,10],[6,30], [5,20]])

我希望将它们合并到一个数组中,如下所示:

[[ 1  2 10]
[ 5 0 20]
[ 6 4 30]]

有人知道按第 0 列的值合并 2 个数组的非迭代模式吗?

我只找到了这种方法:

import numpy as np

a = np.array([[1,2], [5,0], [6,4]])
b = np.array([[1,10],[6,30], [5,20]])
new0col = np.zeros((a.shape[0],1), dtype=int)
a = np.append(a, new0col, axis=1)
l1 = a[:,0].tolist()
l2 = b[:,0].tolist()
for i in l2:
a[l1.index(i),2] = b[l2.index(i),1]
print(a)

最佳答案

您可以使用numpy.searchsorted :

c = np.c_[a, b[np.searchsorted(a[:, 0], b[:, 0]), 1]]

print(c)

array([[ 1, 2, 10],
[ 5, 0, 20],
[ 6, 4, 30]])

将其分解,请注意应用于 b 的行索引会检索 a[:, 0]b[:, 0] 中每个值的索引]:

print(np.searchsorted(a[:, 0], b[:, 0]))

[0 2 1]

关于python - 如何使用列的值将 2 个 numpy ndarray 合并到 ndarray 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51371018/

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