如何按多维数组的第一列搜索唯一元素 [英] how to search for unique elements by the first column of a multidimensional array

查看:52
本文介绍了如何按多维数组的第一列搜索唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法,如何通过仅获取第一列中唯一的元素来从多维数组创建新数组,例如,如果我有一个数组

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.

谢谢

推荐答案

由于您希望保留第一行第一列唯一性,您只需使用 np.unique 及其可选的 return_index 参数,它将为您提供 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屋!

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