如何通过多维数组的第一列搜索唯一元素 [英] how to search for unique elements by the first column of a multidimensional array
问题描述
我试图找到一种方法,通过仅采用第一列中唯一的元素(例如,如果我有一个数组)来从多维数组创建新数组
I am trying to find a way how to create a new array from a multidimensional array by taking only elements that are unique in the first column, for example if I have an array
[[1,2,3],
[1,2,3],
[5,2,3]]
手术后我想得到这个输出
After the operation I would like to get this output
[[1,2,3],
[5,2,3]]
很显然,第二,三列不必是唯一的.
Obviously the second an third columns do not need to be unique.
谢谢
推荐答案
由于您希望保留第一列唯一性的第一行,因此您可以使用<一个href ="http://docs.scipy.org/doc/numpy-1.10.1/reference/generation/numpy.unique.html" rel ="nofollow"> np.unique
及其可选的A[:,0]
元素的唯一性中的第一个出现的索引(因此满足第一行条件),其中A
是输入数组.因此,我们将有一个矢量化的解决方案,像这样-
Since you are looking to keep the first row of first column uniqueness, you can just use np.unique
with its optional return_index
argument which will give you the first occurring index (thus fulfils the first row criteria) among the uniqueness on A[:,0]
elements, where A
is the input array. Thus, we would have a vectorized solution, like so -
_,idx = np.unique(A[:,0],return_index=True)
out = A[idx]
样品运行-
In [16]: A
Out[16]:
array([[1, 2, 3],
[5, 2, 3],
[1, 4, 3]])
In [17]: _,idx = np.unique(A[:,0],return_index=True)
...: out = A[idx]
...:
In [18]: out
Out[18]:
array([[1, 2, 3],
[5, 2, 3]])
这篇关于如何通过多维数组的第一列搜索唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!