Home > Back-end >  How to make if else condition in python 2d array
How to make if else condition in python 2d array

Time:11-21

I have a 2d array with shape(3,6), then i want to create a condition to check a value of each array. my data arry is as follows :

array([[ 1, 2, 3, 4, 5, 6], 7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]])

if in an array there are numbers < 10 then the value will be 0

the result I expected

array([[ 0, 0, 0, 0, 0, 0], 0, 0, 0, 10, 11, 12], [13, 14, 15, 16, 17, 18]])

the code i created is like this, but why can't it work as i expected

FCDataNew = []

a = [ [1,2,3,4,5,6], 
     [7,8,9,10,11,12], 
     [13,14,15,16,17,18]
     ]

a = np.array(a)

c = 0
c = np.array(c)

for i in range(len(a)):
  if a[i].all()<10:
    FCDataNew.append(c)
  else:
    FCDataNew.append(a[i])

FCDataNew = np.array(FCDataNew)
FCDataNew

CodePudding user response:

If you want to modify the array in place, use boolean indexing:

FCDataNew = np.array([[1,2,3,4,5,6],
                      [7,8,9,10,11,12],
                      [13,14,15,16,17,18],
                     ])

FCDataNew[FCDataNew<10] = 0

For a copy:

out = np.where(FCDataNew<10, 0, FCDataNew)

Output:

array([[ 0,  0,  0,  0,  0,  0],
       [ 0,  0,  0, 10, 11, 12],
       [13, 14, 15, 16, 17, 18]])

CodePudding user response:

You can just use arr[arr < 10] = 0

  • Related