将元素附加到数组的数组

Append an element to Array of Arrays

假设我有一个数组数组。

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

我想添加 10 作为每个没有 运行 for 循环的数组的第一个元素。结果应该类似于

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

普通追加不起作用。

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

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

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

np.insert(x, 0, [10,10,10], axis=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]])