0

I have an one-dimensional array A, such that 0 <= A[i] <= 11, and I want to map A to an array B such that

for i in range(len(A)):
    if 0 <= A[i] <= 2: B[i] = 0
    elif 3 <= A[i] <= 5: B[i] = 1
    elif 6 <= A[i] <= 8: B[i] = 2
    elif 9 <= A[i] <= 11: B[i] = 3

How can implement this efficiently in numpy?

2
  • Both arrays are one-dimensionnal, and that code is in a for-loop ? Commented Mar 20, 2021 at 22:04
  • @azro thanks for pointing out. I have edited the question. Commented Mar 20, 2021 at 22:08

5 Answers 5

2

You need to use an int division by //3, and that is the most performant solution

A = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
B = A // 3

print(A)  # [0  1  2  3  4  5  6  7  8  9 10 11]
print(B)  # [0  0  0  1  1  1  2  2  2  3  3  3]
Sign up to request clarification or add additional context in comments.

Comments

1

I would do something like dividing the values of the A[i] by 3 'cause you're sorting out them 3 by 3, 0-2 divided by 3 go answer 0, 3-5 go answer 1, 6-8 divided by 3 is equal to 2, and so on

I built a little schema here:

A[i] --> 0-2. divided by 3 = 0, what you wnat in array B[i] is 0, so it's ok A[i] --> 3-5. divided by 3 = 1, and so on. Just use a method to make floor the value, so that it don't become float type.

1 Comment

good thinkin' np.array([2,5,6,7,8,11])//3 => array([0, 1, 2, 2, 2, 3])
1

Answers provided by others are valid, however I find this function from numpy quite elegant, plus it allows you to avoid for loop which could be quite inefficient for large arrays

import numpy as np

bins = [3, 5, 8, 9, 11]
B = np.digitize(A, bins)

3 Comments

Nice but about 10x times slower than //3
I think this function is very helpful when the numbers are not in an equal gap of 3 for example.
right @azro, but it is a general purpose solution. If a single interval don't respect the length-3 rule, other solutions won't be 'scalable'
0

Something like this might work:

C = np.zeros(12, dtype=np.int)
C[3:6] = 1
C[6:9] = 2
C[9:12] = 3

B = C[A]

Comments

0

If you hope to expand this to a more complex example you can define a function with all your conditions:

def f(a):
    if 0 <= a and a <= 2:
        return 0
    elif 3 <= a and a <= 5:
        return 1
    elif 6 <= a and a <= 8:
        return 2
    elif 9 <= a and a <= 11:
        return 3

And call it on your array A:

A = np.array([0,1,5,7,8,9,10,10, 11])
B = np.array(list(map(f, A))) # array([0, 0, 1, 2, 2, 3, 3, 3, 3])

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.