【问题标题】:Append an element to Array of Arrays将元素附加到数组数组
【发布时间】:2021-07-04 22:42:16
【问题描述】:

假设我有一个数组数组。

import numpy as np
x = np.array([ [1, 2], [3, 4], [5, 6]])

我想在不运行 for 循环的情况下添加 10 作为每个数组的第一个元素。结果应该是这样的

array([[10, 1, 2],
       [10, 3, 4],
       [10, 5, 6]])

普通追加不起作用。

np.append(10, x)
array([10,  1,  2,  3,  4,  5,  6])

我原来的问题有 100K 数组。所以我需要找到一种有效的方法来做到这一点。

【问题讨论】:

  • 那不是数组数组。

标签: python arrays append


【解决方案1】:

np.insert 是你的选择

>>> import numpy as np
x = np.array([ [1, 2], [3, 4], [5, 6]])

>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])

>>> np.insert(x, 0, 10, axis=1)

array([[10,  1,  2],
       [10,  3,  4],
       [10,  5,  6]])

你也可以插入不同的值

>>> np.insert(x, 0, [10,11,12] , axis=1)

array([[10,  1,  2],
       [11,  3,  4],
       [12,  5,  6]])

【讨论】:

    【解决方案2】:

    您正在寻找 np.insert。 https://numpy.org/doc/stable/reference/generated/numpy.insert.html

    np.insert(x, 0, [10,10,10], axis=1)

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2014-02-24
      • 1970-01-01
      • 2020-07-07
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      相关资源
      最近更新 更多