首页 > 解决方案 > 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 的信息,但无法使用它。

标签: pythonnumpy

解决方案


下面是如何使用 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}

推荐阅读