ege Selcuk
ege Selcuk

Reputation: 237

Storing values for each iteration Numpy Python

The code down below goes through the Vals function and it assorts through the Numbers value and adds up all the sums after the sorting. I am trying to append the SUM values to the T_SUM to store the values of each SUM for each sort.

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])
T_Sum = np.array([])
p= 0 

while len(Vals) != p:
    Numbers= np.where(Numbers >= Vals[p],Numbers ,0 )
    p = p + 1
    SUM = np.sum(Numbers)
    T_Sum = np.concatenate((T_Sum, SUM))

print(T_Sum)

Upvotes: 3

Views: 131

Answers (2)

Ehsan
Ehsan

Reputation: 12407

You can use masked arrays to mask values you desire and then sum them up all in one line:

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

output:

array([1167.28664878, 1167.28664878, 1102.28664878, 1102.28664878,
       1102.28664878, 1102.28664878, 1012.78626406,  922.28669704,
        727.9906542 ])

Upvotes: 2

user15270287
user15270287

Reputation: 1153

This should do the same thing:

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])
T_sum = np.empty(len(Vals))
count = 0

for i in Vals:
    Numbers= np.where(Numbers >= Vals[p],Numbers ,0 )
    SUM = np.sum(Numbers)
    T_sum[count] = SUM
    count += 1

Upvotes: 1

Related Questions