Numpy - add row to array

后端 未结 10 1368
难免孤独
难免孤独 2020-11-27 10:59

How does one add rows to a numpy array?

I have an array A:

A = array([[0, 1, 2], [0, 2, 0]])

I wish to add rows to this array from

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 11:35

    As this question is been 7 years before, in the latest version which I am using is numpy version 1.13, and python3, I am doing the same thing with adding a row to a matrix, remember to put a double bracket to the second argument, otherwise, it will raise dimension error.

    In here I am adding on matrix A

    1 2 3
    4 5 6
    

    with a row

    7 8 9
    

    same usage in np.r_

    A= [[1, 2, 3], [4, 5, 6]]
    np.append(A, [[7, 8, 9]], axis=0)
    
        >> array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
    #or 
    np.r_[A,[[7,8,9]]]
    

    Just to someone's intersted, if you would like to add a column,

    array = np.c_[A,np.zeros(#A's row size)]

    following what we did before on matrix A, adding a column to it

    np.c_[A, [2,8]]
    
    >> array([[1, 2, 3, 2],
              [4, 5, 6, 8]])
    

提交回复
热议问题