scipy.sparse
矩阵获取此类信息,但仅适用于 2d
sparse.coo_matrix((data, (row, col)))
where row
and col
指数像你的吗X
,Y
and Z
。它对重复项求和。
这样做的第一步是lexical
指数的排序。这会将具有匹配坐标的点彼此相邻。
我相信,实际的分组和求和是在编译的代码中完成的。做到这么快的部分困难在于numpy
术语是每个组中的元素数量是可变的。有些是唯一的,有些可能有 3 个或更多。
Python itertools
has a groupby
工具。 Pandas 还具有分组功能。我也可以想象使用default_dict
对值进行分组和求和。
The ufunc
reduceat
也可能有效,尽管在 1d 中使用比在 2 或 3 中更容易使用。
如果你忽略了Z
, 稀疏的coo_matrix
方法可能是最简单的。
In [2]: X=np.array([13,9,15,13,13,15])
In [3]: Y=np.array([7,2,3,7,7,3])
In [4]: A=np.array([1.5,0.5,1.1,0.9,1.7,1.1])
In [5]: M=sparse.coo_matrix((A,(X,Y)))
In [15]: M.sum_duplicates()
In [16]: M.data
Out[16]: array([ 0.5, 2.2, 4.1])
In [17]: M.row
Out[17]: array([ 9, 15, 13])
In [18]: M.col
Out[18]: array([2, 3, 7])
In [19]: M
Out[19]:
<16x8 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in COOrdinate format>
这就是我对 lexsort 的想法
In [32]: Z=np.array([21,7,9,21,21,9])
In [33]: xyz=np.stack([X,Y,Z],1)
In [34]: idx=np.lexsort([X,Y,Z])
In [35]: idx
Out[35]: array([1, 2, 5, 0, 3, 4], dtype=int32)
In [36]: xyz[idx,:]
Out[36]:
array([[ 9, 2, 7],
[15, 3, 9],
[15, 3, 9],
[13, 7, 21],
[13, 7, 21],
[13, 7, 21]])
In [37]: A[idx]
Out[37]: array([ 0.5, 1.1, 1.1, 1.5, 0.9, 1.7])
当像这样排序时,更明显的是Z
坐标是“冗余的”,至少对于这个目的而言。
Using reduceat
对组求和:
In [40]: np.add.reduceat(A[idx],[0,1,3])
Out[40]: array([ 0.5, 2.2, 4.1])
(现在我只关注 [0,1,3] 列表)