0

I am trying to calculate the T_Sum value so that for the values that are greater than the Vals values in Numbers it will just add up to the Vals values for that element. For example, the first element of Vals is 60 and all the values within Numbers are greater than 60 (11 in total), so the result will be 60 * 11. If the Vals value is 105 there are 5 elements that are greater than 105 so the result will be 525. How can I do this without a for loop?

Vals = np.arange(start=60, stop=105, step=5)
Numbers = np.array([123.6, 130, 150, 110.3748, 111.6992976,
 102.3165566, 97.81462811, 89.50038472, 96.48141473, 90.49956702, 65])

My attempt

T_Sum = np.ma.masked_array(np.repeat(Numbers[None,:],Vals.size,0),mask=[Numbers<Vals[:,None]]).sum(-1).data

Expected Output

[660, 650, 700, 750, 800, 850, 810, 760, 600, 525]
4
  • 'there are 5 elements that are greater than 6' what do you mean by that? Commented Mar 3, 2021 at 23:47
  • It was supposed to be 60. I updated the issue. Commented Mar 4, 2021 at 0:02
  • Sorry about that i have updated it, i think it should be good now. Commented Mar 4, 2021 at 2:55
  • Yes fixed it sorry lol Commented Mar 4, 2021 at 3:08

2 Answers 2

1

The end value of np.arange must be greater than 105, because it's not end inclusive.

Vals = np.arange(60, 106, 5)
T_Sum = (Numbers[:,None] > Vals).sum(axis=0) * Vals
Sign up to request clarification or add additional context in comments.

Comments

-1

The arrange method is not inclusive of the stop value, so your Vals actually ends at 100, not 105 like you seem to think ti does.

In any case, this will do what you want, just have to play with the start/stop values to get the final result you are looking for.

import numpy as np
Vals= np.arange(start=60, stop=105, step=5)
from collections import Counter
Numbers = np.array([123.6,       130 ,       150,        110.3748,     111.6992976,
 102.3165566,   97.81462811 , 89.50038472 , 96.48141473 , 90.49956702, 65])


output = []

for v in Vals:
    c = 0
    for n in Numbers:
        if n>v:
            c+=1
    print(f'There are {c}, values greater than {v}')
    output.append(c*v)

print(output)

Output

There are 11, values greater than 60
There are 10, values greater than 65
There are 10, values greater than 70
There are 10, values greater than 75
There are 10, values greater than 80
There are 10, values greater than 85
There are 9, values greater than 90
There are 8, values greater than 95
There are 6, values greater than 100
[660, 650, 700, 750, 800, 850, 810, 760, 600]

1 Comment

I am trying to use a numpy function to do that, since for lops arent optimized well and are slow, but thanks anyways.

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.