【问题标题】:How to merge two numpy arrays for each number in the first?如何为第一个中的每个数字合并两个 numpy 数组?
【发布时间】:2022-01-08 20:23:37
【问题描述】:

我有两个数组,例如a = [1, 2] 和 b = [3, 4]。我想要的是为每个 a 创建一个包含所有 b 的数组:c = [[1, 3], [1, 4], [2, 3], [2, 4]]。我如何使用 numpy 做到这一点?

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

使用np.meshgrid:

import numpy as np

a = [1, 2]
b = [3, 4]


def mesh(values):
    return np.array(np.meshgrid(*values)).T.reshape(-1, len(values))


res = mesh([a, b])
print(res)

输出

[[1 3]
 [1 4]
 [2 3]
 [2 4]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多