我有一个由LAS数据 [x,y,z,intensity,classification]
组成的numpy数组filtered__rows
。 我创建了一个点的cKDTree
并找到了最近的邻居 query_ball_point
,它是点及其邻居的索引列表。
有没有办法过滤filtered__rows
,创建仅包含在query_ball_point
返回的列表中的索引的数组?
我有一个由LAS数据 [x,y,z,intensity,classification]
组成的numpy数组filtered__rows
。 我创建了一个点的cKDTree
并找到了最近的邻居 query_ball_point
,它是点及其邻居的索引列表。
有没有办法过滤filtered__rows
,创建仅包含在query_ball_point
返回的列表中的索引的数组?
看起来你只需要基本的整数数组索引:
filter_indices = [1,3,5]
np.array([11,13,155,22,0xff,32,56,88])[filter_indices]
numpy.take
对多维数组非常有用且效果良好。
import numpy as np
filter_indices = [1, 2]
array = np.array([[1, 2, 3, 4, 5],
[10, 20, 30, 40, 50],
[100, 200, 300, 400, 500]])
axis = 0
print(np.take(array, filter_indices, axis))
# [[ 10 20 30 40 50]
# [100 200 300 400 500]]
axis = 1
print(np.take(array, filter_indices, axis))
# [[ 2 3]
# [ 20 30]
# [200 300]]
使用文档:https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html 以下实现适用于一些numpy ndarry任意数量的维度/形状。
首先,我们需要一个多维索引集和一些示例数据:
import numpy as np
y = np.arange(35).reshape(5,7)
print(y)
indexlist = [[0,1], [0,2], [3,3]]
print ('indexlist:', indexlist)
要提取直观结果,诀窍是使用Transpose:
indexlisttranspose = np.array(indexlist).T.tolist()
print ('indexlist.T:', indexlisttranspose)
print ('y[indexlist.T]:', y[ tuple(indexlisttranspose) ])
使终端输出以下内容:y: [[ 0 1 2 3 4 5 6]
[ 7 8 9 10 11 12 13]
[14 15 16 17 18 19 20]
[21 22 23 24 25 26 27]
[28 29 30 31 32 33 34]]
indexlist: [[0, 1], [0, 2], [3, 3]]
indexlist.T: [[0, 0, 3], [1, 2, 3]]
y[indexlist.T]: [ 1 2 24]
print ('y[indexlist.T]:', y[ indexlisttranspose ])
FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`.
In the future this will be interpreted as an array index,
`arr[np.array(seq)]`, which will result either in an error or a
different result.
print ('y[indexlist.T]:', y[ indexlisttranspose ])
y[indexlist.T]: [ 1 2 24]
你知道如何将它应用到多维数组吗?
可以通过为每个索引提供一个一维数组来扩展到多维数组,例如对于一个二维数组:
filter_indices=np.array([[1,0],[0,1]])
array=np.array([[0,1],[1,2]])
print(array[filter_indices[:,0],filter_indices[:,1]])
将会给你返回:[1,1]
Scipy对调用以下代码的结果进行了解释:
print(array[filter_indices])
文档 - https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html
最快的方法是使用X[tuple(index.T)]
,其中X
是包含元素的ndarray,index
是希望检索的索引的ndarray。
X[tuple(index), :]
。 - Shivam Chaudhary