首页 > 解决方案 > 在 Python 中从 2 个单维数组创建 2d 数组

问题描述

我有 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])

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

标签: arrayspython-3.xnumpy

解决方案


要从参差不齐的嵌套序列创建 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])

或使用数组

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])

推荐阅读