python - Python Numpy在其他数组给出的索引上优化计算数组的平均值
问题描述
如何使用来自另一个数组的 x 索引计算 numpy 数组 y 的平均值?
import numpy
x = numpy.array([100, 100, 20000, 20000, 100, 13, 100, numpy.nan])
y = numpy.array([10, 20, 30, 40, numpy.nan, 50, 60, 70])
预期结果:
result['13']: (50)/1
result['100']: (10+20+60)/3
result['20000']: (30+40)/2
以下代码有效,但由于我的真实数据集的大小而效率不高:
result = {}
unique = numpy.unique(x[~numpy.isnan(x)]).astype(int)
for elem in unique:
pos = numpy.where(x == elem)
avg = numpy.nanmean(y[pos])
result[elem]=avg
print(result)
我读过有关 numpy.bincount 的信息,但无法使用它。
解决方案
下面是如何使用 bincount:
>>> nn=~(np.isnan(x)|np.isnan(y))
>>> xr,yr = x[nn],y[nn]
>>> unq,idx,cnt=np.unique(xr,return_inverse=True,return_counts=True)
>>> dict(zip(unq,np.bincount(idx,yr)/cnt))
{13.0: 50.0, 100.0: 30.0, 20000.0: 35.0}
推荐阅读
- javascript - 将信息从 rest API 发送到 arduino 正确编码
- raspberry-pi - 谷歌助手树莓派问题 | 启动指令不起作用
- javascript - 在页面加载时,在 DIV 中填充随机颜色。用随机颜色填充另外 4 个 div... 点击这 4 个 div 中的任何一个,以 9:1 的比例填充主 div
- turing-machines - 图灵机转换表
- java - 如何在java中的方法参数中传递类类型
- javascript - 与另一个对象相交时应该调用动作的循环类的问题
- c++ - C++ Boost 侵入式列表 - 示例
- python - Python中的快速排序递归
- haskell - 这个错误在haskell中不断发生关于如何修复它的任何想法?
- android - 如何在 OnPreferenceChange 中保存另一个值而不是 newValue?