Home > Blockchain >  Can I replace values in ndarray by np.where with condition?
Can I replace values in ndarray by np.where with condition?

Time:04-10

I have a 2d array,such as

         5.        ,  6.        ,  7.        ,  8.        ,  9.        ],
       [-0.6810069 , -0.61737489,  0.09869664, -0.95659638,  0.54052288,
        -0.21486195, -0.55328357, -0.41680664,  0.60628816, -0.92563772],
       [ 0.54264171,  0.52459383, -0.83691756,  0.66207278, -0.65591567,
        -0.72713526, -0.66719761, -0.99448398,  0.06691338, -0.2620483 ]])

I need to change value, if arr[1] < 0 & arr[2] < 0 then arr[0] 10 else arr[1] < 0 & arr[2] > 0 then arr[0] - 10. I try to change by lower code:

arr[:,np.where(arr[1] < 0 & arr[1] < 0)][0]  = 10

but failed.the origin array doesn't change, but the code return a result which I need.Help me plz!!!

CodePudding user response:

You can break things into 2 steps (I'm using n to denote the array):

# Find the columns satisfying the given conditions
column_indices_1 = np.where(np.logical_and(n[1] < 0, n[2] < 0))
column_indices_2 = np.where(np.logical_and(n[1] < 0, n[2] > 0))

# Change the elements in the columns meeting the conditions
n[0, column_indices_1]  = 10
n[0, column_indices_2] -= 10
  • Related