2

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

2 Answers 2

2

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]])
Sign up to request clarification or add additional context in comments.

11 Comments

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) out = np.where(FCDataNew<10, 0, FCDataNew)
Is it like this?
No, just what I wrote in the answer, no need for a loop
but how if in the case I have negative value?
array([[ -8, -2, 3, 4, -1, 2], [ 7, -1, -2, -1, 10, -3], [13, 14, 15, 16, 17, 18]])
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.