简体   繁体   English

平均列表 A 的所有元素,其索引在列表 B 中具有相同的值

[英]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.

相关问题 在列表中打印与列表的平均值具有相同平均值的元素对 - Print pairs of elements in a list that have the same average value as the list's average value 修改索引由没有 for 循环的列表定义的列表元素 - Modify list elements whose indices are defined by a list without a for loop 查找列表中其字段与值匹配的所有元素 - Find all the elements of a list whose field match with a value 元组列表中具有相同索引的所有元素的平均值 - Average of all elements in tuple list having the same index 从列表中提取与包含在第三个列表中的另一个列表的项具有相同索引的值 - Extract values from a list that have the same indices as the items of another list which are contained in a third list for loop + List in Lists 导致所有索引的值相同 - for loop + List in Lists leading to same value for all indices 获取其值总计为给定数字的列表的索引 - Get the indices of a list whose value add up to the given number 对列表中相同元素的索引进行分组的有效方法 - Efficient way to group indices of the same elements in a list 检查列表B中列表A的所有元素 - Check if ALL elements of list A within list B 用包含所有唯一元素的列表索引替换列表中的元素 - Replacing elements in a list with the indices of a list containing all unique elements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM