Home > Enterprise >  New values for intervals of numbers
New values for intervals of numbers

Time:04-28

I have numpy arrays that look like this:

[2.20535093 2.44367784]
[7.20467093 1.54379728]
.
.
.
etc

I want to take each array and convert it like this:

[1 1]
[2 0]

0 means that the values are below 2. 1 means that the values are between 1 and 3. 2 means they are above 3.

I want to use a switch case function in python for this. This is what I wrote until now:

def intervals(input):
    match input:
        case num if 0 <= num.all() < 2:
            input = 0
        case num if 2 <= num.all() < 3:
            input = 1
        case num if 3 <= num.all() <= math.inf:
            input = 2
    return input

But it doesn't seem to work as expected.

CodePudding user response:

Without using a switch case, you can use:

num = np.array([[2.20535093, 2.44367784],
             [7.20467093, 1.54379728]])
print(num)   # [[2.20535093 2.44367784], [7.20467093 1.54379728]]

num[num < 2] = 0
num[np.logical_and(num > 1, num < 3)] = 1
num[num > 3] = 2
print(num)   # [[1 1], [2 0]]

CodePudding user response:

Your first two conditions are in conflict, since a value could be at the same time below 2 and between 1 and 3. Assuming the "below 2" condition wins in this case, a one line solution to your problem could be like that:

import numpy as np
arr = np.random.rand(5000000, 2)

new_arr = (arr > 2)   (arr > 3)

Here you are assigning 1 if value is above 2 and 1 if value is above 3 (Trues are casted to int and summed).

The approach is also slightly faster that other proposed solution, though less readable.

  • Related