numpy的:对应于独特的坐标位置值的平均 [英] Numpy: Average of values corresponding to unique coordinate positions

查看:244
本文介绍了numpy的:对应于独特的坐标位置值的平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直在浏览计算器很长一段时间了,但我似乎无法找到我的问题的解决方案。

So, I have been browsing stackoverflow for quite some time now, but I can't seem to find the solution for my problem

考虑这个

import numpy as np
coo = np.array([[1, 2], [2, 3], [3, 4], [3, 4], [1, 2], [5, 6], [1, 2]])
values = np.array([1, 2, 4, 2, 1, 6, 1])

首席运营官数组包含(x,y)坐标位置
X =(1,2,3,3,1,5,1)
Y =(2,3,4,4,2,6,2)

The coo array contains the (x, y) coordinate positions x = (1, 2, 3, 3, 1, 5, 1) y = (2, 3, 4, 4, 2, 6, 2)

和值数组某种数据的该网格点。

and the values array some sort of data for this grid point.

现在我想要得到的所有值的平均值为每一个独特的网格点。
例如坐标(1,2)在该位置发生(0,4,6),因此,对于这一点,我想值[0,4,6]]

Now I want to get the average of all values for each unique grid point. For example the coordinate (1, 2) occurs at the positions (0, 4, 6), so for this point I want values[[0, 4, 6]].

我怎么能得到这个所有独特的网格点?

How could I get this for all unique grid points?

推荐答案

您可以排序 COO np.lexsort 带来的重复那些在继承。然后运行 np.diff 沿行获得的唯一XY的开始面具在排序版本。使用面膜,你可以创建一个ID阵列,将有对于重复相同的ID。 ID数组然后可以用 使用NP .bincount 得到相同ID的所有值以及它们的数量,从而平均值的总和,作为最终输出。下面是沿着这些线路去实现 -

You can sort coo with np.lexsort to bring the duplicate ones in succession. Then run np.diff along the rows to get a mask of starts of unique XY's in the sorted version. Using that mask, you can create an ID array that would have the same ID for the duplicates. The ID array can then be used with np.bincount to get the summation of all values with the same ID and also their counts and thus the average values, as the final output. Here's an implementation to go along those lines -

# Use lexsort to bring duplicate coo XY's in succession
sortidx = np.lexsort(coo.T)
sorted_coo =  coo[sortidx]

# Get mask of start of each unique coo XY
unqID_mask = np.append(True,np.any(np.diff(sorted_coo,axis=0),axis=1))

# Tag/ID each coo XY based on their uniqueness among others
ID = unqID_mask.cumsum()-1

# Get unique coo XY's
unq_coo = sorted_coo[unqID_mask]

# Finally use bincount to get the summation of all coo within same IDs 
# and their counts and thus the average values
average_values = np.bincount(ID,values[sortidx])/np.bincount(ID)

样运行 -

In [65]: coo
Out[65]: 
array([[1, 2],
       [2, 3],
       [3, 4],
       [3, 4],
       [1, 2],
       [5, 6],
       [1, 2]])

In [66]: values
Out[66]: array([1, 2, 4, 2, 1, 6, 1])

In [67]: unq_coo
Out[67]: 
array([[1, 2],
       [2, 3],
       [3, 4],
       [5, 6]])

In [68]: average_values
Out[68]: array([ 1.,  2.,  3.,  6.])

这篇关于numpy的:对应于独特的坐标位置值的平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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