[[1,1,2], [1,3,4],[1,5,6]]
    
1 个评论
这是否回答了你的问题?如何在NumPy数组中增加一个额外的列
python
numpy
numpy-ndarray
Moose
Moose
发布于 2019-12-01
4 个回答
azro
azro
发布于 2019-12-02
已采纳
0 人赞同
  • 你可以使用np.insert

    new_x = np.insert(x, 0, 1, axis=1)
    
  • 你可以使用np.append方法在一列1值的右边添加你的数组

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

    Both will give you the expected result

    [[1 1 2]
     [1 3 4]
     [1 5 6]]
        
  • Arkistarvh Kltzuonstev
    Arkistarvh Kltzuonstev
    发布于 2019-12-02
    0 人赞同

    Try this:

    >>> X = np.array([[1, 2], [3, 4], [5, 6]])
    array([[1, 2],
           [3, 4],
           [5, 6]])
    >>> np.insert(X, 0, 1, axis=1)
    array([[1, 1, 2],
           [1, 3, 4],
           [1, 5, 6]])
        
    NaN
    NaN
    发布于 2019-12-02
    0 人赞同

    因为无论如何都要创建一个新的数组,只是有时从一开始就这样做比较容易。 既然你想在开始时有一列1,那么你可以使用内置函数和输入数组的现有结构和dtype。

    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
    array([[1, 0, 1],
           [1, 2, 3],
           [1, 4, 5]])
        
    Sammyak Sangai
    Sammyak Sangai
    发布于 2019-12-02
    0 人赞同

    numpy.insert() will do the trick.

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

    The Output will be:

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