[SOLVED] how to add rows to a numpy array

Issue

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.

Solution

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

Answered By – joanis

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *