Home > Software design >  How do I filter specific number using `np.where`
How do I filter specific number using `np.where`

Time:12-11

Case

enter image description here

so I have an array like these, and how do I extract the green number from the array?

The output that I wanted :

[11, 13, 15, 21, 23, 25, 31, 33, 35]

My code to make the array:

a = np.arange(start=11, stop=36, step=1)

My code for filtering:

print(a[np.where((a % 2 == 1))])

CodePudding user response:

Hope I answered your question..

array = np.array(

              [[11, 12, 13, 14, 15],

              [16, 17, 18, 19, 20],

              [21, 22, 23, 24, 25],

              [26, 27, 28, 29, 30],

              [31, 32, 33, 34, 35]])

filter1 = array[:, [0, 2, 4]]
filter2 = filter1[[0, 2, 4], :].flatten()

>>[11 13 15 21 23 25 31 33 35]

CodePudding user response:

An alternative approach using just lists:

from functools import reduce

board = [[x * 5   10   y for y in range(1, 6)] for x in range(0, 5)]

reduce(lambda x, y: x   y, list(zip(*board[0:5:2]))[0:5:2])

OUTPUT

(11, 21, 31, 13, 23, 33, 15, 25, 35)

Alternatively, you could use something like:

[board[y-1][x-1] for x in range(1,6) for y in range(1,6) if x * y % 2 == 1]

OUTPUT

[11, 21, 31, 13, 23, 33, 15, 25, 35]
  • Related