0

I am trying to code a function where it checks if the Numbers elements are between the Formating values. So for the first element of Numbers 3 is not between the first and the second element 0, 2 of Formating so it returns 0 as the result. For the elements 3,4 in Numbers are between 2 ,5 so it return those 3,4 as the numbers between 2,5. The index value keeps on getting incremented until the end of the Formating array. How could I fix the function below so it gives the expected output, without a for loop.

Numbers = np.array([3, 4, 5, 7, 8, 10,20])
Formating = np.array([0, 2 , 5, 12, 15, 22])

#previouse and curent index values 
prevs = np.arange(0,len(Formating)-1,1)
currents = np.arange(1,len(Formating),1)
index = 0

np.where(Formating[prevs[index]] <= Numbers < Formating[currents[index]], Numbers, ++index)

Expected Output:

Numbers between 0,2 = 0
Numbers between 2,5 = 3,4
Numbers between 5,12 = 5,7,8,10
Numbers between 12,15 = 0
Numbers between 15,22 = 20
2
  • Something with np.histogram(Numbers, bins=Formating) or np.digitize(Numbers, Formating)? Commented Mar 10, 2021 at 19:23
  • Usually formatting refers to converting numbers to strings, as in %d%3` or {}.format(3). Your use of Formating as an array, as though it means something, is misleading, and may discourage useful answers. Numbers isn't that great of a variable either (it looks more like a class name). Commented Mar 10, 2021 at 21:00

1 Answer 1

0

You could sort then search sorted and it will run more efficiently (except for the IO)


Numbers = np.array([3, 4, 5, 7, 8, 10,20])
Formating = np.array([0, 2 , 5, 12, 15, 22])
x = np.sort(Numbers);
l = np.searchsorted(x, Formating, side='left')

for i in range(len(l)-1):
    if l[i] >= l[i+1]:
        print('Numbers between %d,%d = _0_' % (Formating[i], Formating[i+1]))
    else:
        print('Numbers between %d,%d = %s' % (Formating[i], Formating[i+1], ','.join(map(str, list(x[l[i]:l[i+1]])))))
Sign up to request clarification or add additional context in comments.

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.