如何向numpy数组添加列

3
如何在第二个numpy数组的开头添加一个仅包含“1”的列。
X = np.array([1, 2], [3, 4], [5, 6])

我希望让X变成

[[1,1,2], [1,3,4],[1,5,6]]

这个回答解决了你的问题吗?如何向NumPy数组添加额外的列 - undefined
4个回答

2
  • You can use the np.insert

    new_x = np.insert(x, 0, 1, axis=1)
    
  • You can use the np.append method to add your array at the right of a column of 1 values

    x = np.array([[1, 2], [3, 4], [5, 6]])
    ones = np.array([[1]] * len(x))
    new_x = np.append(ones, x, axis=1)
    

两者都会给你期望的结果。

[[1 1 2]
 [1 3 4]
 [1 5 6]]

1

试试这个:

>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> X
array([[1, 2],
       [3, 4],
       [5, 6]])

>>> np.insert(X, 0, 1, axis=1)
array([[1, 1, 2],
       [1, 3, 4],
       [1, 5, 6]])

1

由于无论如何都会创建一个新的数组,所以从一开始就这样做有时更容易。由于您想在开头有一列1,因此可以使用内置函数和输入数组的现有结构和数据类型。

a = np.arange(6).reshape(3,2)               # input array
z = np.ones((a.shape[0], 3), dtype=a.dtype) # use the row shape and your desired columns
z[:, 1:] = a                                # place the old array into the new array
z
array([[1, 0, 1],
       [1, 2, 3],
       [1, 4, 5]])

0

numpy.insert()会解决问题。

X = np.array([[1, 2], [3, 4], [5, 6]])
np.insert(X,0,[1,2,3],axis=1)

输出将是:

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

请注意,第二个参数是您想要插入的位置之前的索引。而axis = 1表示您希望将其作为列插入而不会使数组变平。
参考链接: numpy.insert()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接