How to add an extra column to a NumPy array

前端 未结 17 2080
一个人的身影
一个人的身影 2020-11-22 14:37

Let’s say I have a NumPy array, a:

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

And I would like to add a column of ze

17条回答
  •  耶瑟儿~
    2020-11-22 15:14

    Add an extra column to a numpy array:

    Numpy's np.append method takes three parameters, the first two are 2D numpy arrays and the 3rd is an axis parameter instructing along which axis to append:

    import numpy as np  
    x = np.array([[1,2,3], [4,5,6]]) 
    print("Original x:") 
    print(x) 
    
    y = np.array([[1], [1]]) 
    print("Original y:") 
    print(y) 
    
    print("x appended to y on axis of 1:") 
    print(np.append(x, y, axis=1)) 
    

    Prints:

    Original x:
    [[1 2 3]
     [4 5 6]]
    Original y:
    [[1]
     [1]]
    x appended to y on axis of 1:
    [[1 2 3 1]
     [4 5 6 1]]
    

提交回复
热议问题