[英]Average all of elements of list A which whose indices have the same value in list B
values_array = np.array([2,4,6])
coords_array = np.array([[127,130,130],[127,130,130],[128,131,132]])
Each element v in values_array has a "coordinate" c at the same position in coords_array. values_array 中的每个元素 v 在 coords_array 中的相同 position 处都有一个“坐标”c。
I need a mapping from unique coordinate c to the average of all values which have that coordinate.我需要从唯一坐标 c 到具有该坐标的所有值的平均值的映射。 For the example that would be例如,这将是
mapping[[127,130,130]] = np.mean([2,4])
mapping[[128,131,132]] = np.mean([6])
Without worrying about speed, I would do:不用担心速度,我会这样做:
mapping = {}
for coordinate in np.unique(coords_array):
indices = np.where(coords_array==coordinate)
mapping[coordinate] = np.mean(values_array[indices])
I really need to do it without the loop in python if at all possible though.如果可能的话,我真的需要在没有 python 的循环的情况下做到这一点。
We could use np.unique
to tag each unique color and then bincount
to get labeled average values -我们可以使用np.unique
标记每种唯一颜色,然后使用bincount
来获得标记的平均值 -
In [145]: u,t = np.unique(coords_array, axis=0, return_inverse=True)
# Unique avg colors
In [146]: u
Out[146]:
array([[127, 130, 130],
[128, 131, 132]])
# Avg values
In [147]: np.bincount(t, values_array)/np.bincount(t)
Out[147]: array([3., 6.])
Or additionally, use return_counts
arg to get counts directly -或者另外,使用return_counts
arg 直接获取计数 -
In [156]: u,t,c = np.unique(coords_array, axis=0, return_inverse=True, return_counts=True)
In [159]: np.bincount(t, values_array)/c
Out[159]: array([3., 6.])
So, if you need to assign these average values into a 3D array a
, simply do -因此,如果您需要将这些平均值分配到 3D 数组a
中,只需执行 -
a[tuple(u.T)] = avg # avg are average values from bincount output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.