【问题标题】:Create 2d array from 2 single dimensional array in Python在 Python 中从 2 个单维数组创建 2d 数组
【发布时间】:2021-07-12 07:18:05
【问题描述】:

我有 2 个一维 NumPy 数组

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

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

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

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

编辑:基于@jtwalters cmets 更新循环

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

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

【问题讨论】:

  • [[0,1,2], [4,5]] 不能做成二维数组。
  • np.arange(6).reshape(2,3) 适合你吗?
  • 我同意你的第一条评论。但是np.arange(6).reshape(2,3) 不起作用。 2 行应该是 np.arange(a[i], a[i]+b[i]) 请注意 3 不在我的结果数组中。
  • 我试图从一个令人困惑的例子中弄清楚。
  • 你的循环不起作用。

标签: arrays python-3.x numpy


【解决方案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])

【讨论】:

  • 有没有办法将这个向量化?
  • @deepAgrawal 是的,我用np.vectorize更新代码
猜你喜欢
  • 2018-01-07
  • 1970-01-01
  • 2014-09-25
  • 2023-03-18
  • 2022-07-30
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 2023-01-04
相关资源
最近更新 更多