numpy数组映射并取平均值 [英] numpy array mapping and take average

查看:96
本文介绍了numpy数组映射并取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个数组

import numpy as np
value = np.array ([1, 3, 3, 5, 5, 7, 3])
index = np.array ([1, 1, 3, 3, 6, 6, 6])
data  = np.array ([1, 2, 3, 4, 5, 6])

数组索引"& 值"具有相同的大小,我想通过取平均值将值"中的项目分组.例如:对于值"中的前两个项目[1、3,...,在索引"中具有相同的键1,因此对于最后一个数组,该值是1st和amp的均值.值的第二项:(1 + 3)/2等于2

Arrays "index" & "value" have same size and I want to group the items in "value" by taking average. For example: For the first two items [1, 3, ... in "value", have the same key 1 in "index", so for the final array the value is the mean of the 1st & 2rd items in value : (1 + 3 )/2 which is equal 2

最后一个数组是:

[2, nan, 4, nan, nan, 5]

第一个值是值"的第一个和第二个的平均值.
第二个值是nan,因为索引"中没有任何键(数组索引中没有"2")
第三个值是值"的第3和第4个平均值 ...

first value is the average of 1st and 2nd of "value"
second value is nan because there is not any key in "index" (no "2" in array index)
third value is the average of 3rd and 4th of "value" ...

感谢您的帮助!

关于, 罗伊

推荐答案

也许您想使用numpy.bincount()?

value = np.array([1, 3, 3, 5, 5, 7, 3])
index = np.array([1, 1, 3, 3, 6, 6, 6])
np.bincount(index, value) / np.bincount(index)
# array([ NaN,   2.,  NaN,   4.,  NaN,  NaN,   5.])

这篇关于numpy数组映射并取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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