简体   繁体   中英

Formatting and summing up numbers with arrays

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]

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM