用数组格式化和汇总数字 [英] Formatting and summing up numbers with arrays

查看:37
本文介绍了用数组格式化和汇总数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算 T_Sum 值,以便对于大于 Numbers 中的 Vals 值的值,它只会添加直到该元素的 Vals 值.例如, Vals 的第一个元素是60,并且 Numbers 中的所有值都大于60(总计11),因此结果将是60 * 11. Vals 的值为105,则有5个元素大于105,因此结果为525.如何在没有for循环的情况下执行此操作?

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])

我的尝试

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

预期产量

[660, 650, 700, 750, 800, 850, 810, 760, 600, 525]

推荐答案

np.arange 的结束值必须大于105,因为它不包括结尾.

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

这篇关于用数组格式化和汇总数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆