在 Python 中从 2 个一维数组创建二维数组

时间:2021-07-12 07:18:05

标签: arrays python-3.x numpy

我有 2 个一维 NumPy 数组

a = np.array([0, 4])
b = np.array([3, 2])

我想创建一个二维数字数组

c = np.array([[0,1,2], [4,5]])

我也可以使用 for 循环来创建它

编辑:根据 @jtwalters 条评论更新循环

c = np.zeros(b.shape[0], dtype=object)
for i in range(b.shape[0]):
    c[i] = np.arange(a[i], a[i]+b[i])

如何通过矢量化/广播实现这一目标?

1 个答案:

答案 0 :(得分:1)

要从不规则的嵌套序列创建 ndarray,您必须输入 dtype=object

例如:

c = np.empty(b.shape[0], dtype=object)
for i in range(b.shape[0]):
    c[i] = np.arange(a[i], a[i]+b[i])

或使用array for

np.array([np.arange(a[i], a[i]+b[i]) for i in range(b.shape[0])], dtype=object)

矢量化:

def func(a, b):
  return np.arange(a, a + b)

vfunc = np.vectorize(func, otypes=["object"])
vfunc([0, 4], [3, 2])