Home > Back-end >  how to add rows to a numpy array
how to add rows to a numpy array

Time:03-17

I have a numpy array and want to add a row to it and modify one column. This is my array:

import numpy as np
small_array = np.array ([[[3., 2., 5.],
                          [3., 2., 2.]],
                         [[3., 2., 7.],
                          [3., 2., 5.]]])

Then, firstly I wnat to add a fixed value (e.g. 2.) to last column. I did it this way:

chg = 2.
small_array[:,:,-1]  = chg

next thing that I want to do is adding another row to each aubarray. Added row should have the same first and second columns but third column shold be different. This time chg x 2. should be subtracted from the existing value in third column:

big_array = np.array ([[[3., 2., 7.],
                          [3., 2., 4.],
                          [3., 2., 0.]], # this row is added
                         [[3., 2., 9.],
                          [3., 2., 7.],
                          [3., 2., 3.]]]) # this row is added

I very much appreciate any help to do it.

CodePudding user response:

I believe the operation you are looking for is np.concatenate, which can construct a new array by concatenating two arrays.

Simple example, we can add a row of zeroes like this:

>>> np.concatenate((small_array, np.zeros((2,1,3))), axis=1)
array([[[3., 2., 7.],
        [3., 2., 4.],
        [0., 0., 0.]],

       [[3., 2., 9.],
        [3., 2., 7.],
        [0., 0., 0.]]])

Now, instead of zeros, we can get the values from the first row in each matrix:

>>> np.concatenate((small_array, small_array[:,:1,:]), axis=1)
array([[[3., 2., 7.],
        [3., 2., 4.],
        [3., 2., 7.]],

       [[3., 2., 9.],
        [3., 2., 7.],
        [3., 2., 9.]]])

At this point, you can modify the value in the third column of the new rows as needed.

The axis parameter is important here, it tells concatenate() along which axis I want to concatenate the two input arrays.

Documentation: https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html

CodePudding user response:

have you tried using numpy.resize ?

https://numpy.org/doc/stable/reference/generated/numpy.resize.html

you will have to decide for yourself if this is too computationally expensive, and if a numpy.list makes more sense for your purposes.

for example,

import numpy as np
a = np.array([[1,2], [3,4]])
a = np.resize(a, (3,2))

then use the index to edit the value of the array at the latest position

a[-1]=[8,9]

the final output of this example should be

a
array([[1,2],
      [3,4]
      [8,9]])
  • Related