How to add an extra column to a NumPy array

前端 未结 17 2149
一个人的身影
一个人的身影 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:09

    np.insert also serves the purpose.

    matA = np.array([[1,2,3], 
                     [2,3,4]])
    idx = 3
    new_col = np.array([0, 0])
    np.insert(matA, idx, new_col, axis=1)
    
    array([[1, 2, 3, 0],
           [2, 3, 4, 0]])
    

    It inserts values, here new_col, before a given index, here idx along one axis. In other words, the newly inserted values will occupy the idx column and move what were originally there at and after idx backward.

提交回复
热议问题