Home > other >  Take every odd row of from column A and add 20 to the element in the second column
Take every odd row of from column A and add 20 to the element in the second column

Time:05-17

I have the following matrix.

import numpy as np
array = np.matrix([[2, 2], [4, 4], [1, 6], [6, 8],[7,9],[8,10],[10,12]])

matrix([[ 2,  2],
        [ 4,  4],
        [ 1,  6],
        [ 6,  8],
        [ 7,  9],
        [ 8, 10],
        [10, 12]])

I want to take every odd row from column A and add 20 to the element in the second column. Following is what I am trying to achieve, I have used for loop but without success. Is there a efficient way of doing this ?

matrix([[ 2,  2],
        [ 4,  4],
        [ 1,  26],
        [ 6,  8],
        [ 7,  29],
        [ 8, 10],
        [10, 12]])

CodePudding user response:

This works

# use where to find the rows where the first column values are odd
# and add 20 to the corresponding second column values
array[np.where(array[:,0]%2==1)[0], [1]]  = 20
array
#matrix([[ 2,  2],
#        [ 4,  4],
#        [ 1, 26],
#        [ 6,  8],
#        [ 7, 29],
#        [ 8, 10],
#        [10, 12]])

CodePudding user response:

for i in range(len(array)):
    if (array[i,0]%2) == 1:
        array[i,1] = array[i,1] 20
        
array

OUTPUT:matrix([[ 2,  2],
        [ 4,  4],
        [ 1, 26],
        [ 6,  8],
        [ 7, 29],
        [ 8, 10],
        [10, 12]])
  • Related