gpt4 book ai didi

python - Numpy:对应于唯一坐标位置的值的平均值

转载 作者:太空狗 更新时间:2023-10-29 21:39:31 24 4
gpt4 key购买 nike

所以,我浏览 stackoverflow 已经有一段时间了,但我似乎找不到解决问题的方法

考虑一下

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])

coo 数组包含 (x, y) 坐标位置x = (1, 2, 3, 3, 1, 5, 1)y = (2, 3, 4, 4, 2, 6, 2)

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

现在我想获取每个唯一网格点的所有值的平均值。例如,坐标 (1, 2) 出现在位置 (0, 4, 6),因此对于这一点,我需要 values[[0, 4, 6]]

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

最佳答案

您可以使用 np.lexsortcoo 进行排序连续带来重复的。然后运行 ​​np.diff沿行获取排序版本中唯一 XY 开始的掩码。使用该掩码,您可以创建一个 ID 数组,该数组对重复项具有相同的 ID。然后 ID 数组可以与 np.bincount 一起使用获得具有相同 ID 的所有值的总和以及它们的计数,从而得到平均值,作为最终输出。这是遵循这些思路的实现 -

# 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)

sample 运行-

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.])

关于python - Numpy:对应于唯一坐标位置的值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31878240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com