How can I add an additional row and column to an array?

前端 未结 2 1523
我在风中等你
我在风中等你 2020-12-31 23:14

I need to add a column and a row to an existing Numpy array at a defined position.

2条回答
  •  春和景丽
    2020-12-31 23:37

    There are many ways to do this in numpy, but not all of them let you add the row/column to the target array at any location (e.g., append only allows addition after the last row/column). If you want a single method/function to append either a row or column at any position in a target array, i would go with 'insert':

    T = NP.random.randint(0, 10, 20).reshape(5, 4)
    c = NP.random.randint(0, 10, 5)
    r = NP.random.randint(0, 10, 4)
    # add a column to T, at the front:
    NP.insert(T, 0, c, axis=1)
    # add a column to T, at the end:
    NP.insert(T, 4, c, axis=1)
    # add a row to T between the first two rows:
    NP.insert(T, 2, r, axis=0)
    

提交回复
热议问题