如何使用NumPy数组索引从2D数组中选择2列以从中选择唯一值? [英] How can I use NumPy array indexing to select 2 columns out of a 2D array to select unique values from?

查看:66
本文介绍了如何使用NumPy数组索引从2D数组中选择2列以从中选择唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常愚蠢的问题,但是我已经搜索了并且无法在任何地方找到答案(可能是因为它太愚蠢了).

This is probably a really stupid question, but I have searched and cannot find an answer anywhere (probably because it's too stupid a question).

我有一个包含多个列的2D NumPy数组.我想在1st2nd列中标识unique元素,但不在其余列中标识:

I have a 2D NumPy array with multiple columns. I want to identify unique elements in the 1st or 2nd column, but not in the rest of the columns:

array([['A', 'B', '3', '4'],
       ['C', 'D', '3', '5']], 
      dtype='|S1')

使用np.unique将在数组中获得唯一值,我可以像这样对单个列编制索引:

Using np.unique will get unique values in the array, and I can index a single column like so:

np.unique(example_array[:,0])
Out[16]: 
array(['A', 'C'], 
      dtype='|S1')

如何索引它,以便可以在[;,0][:,1]中找到所有唯一值?

How can I index it so that I can find all the unique values in [;,0] and in [:,1]?

推荐答案

在第二维上也使用:2切片,以包括多个列.

Use a :2 slice on the second dimension as well, to include more than one column.

np.unique(example_array[:,:2])
Out[]: 
array(['A', 'B', 'C', 'D'], 
      dtype='|S1')

这篇关于如何使用NumPy数组索引从2D数组中选择2列以从中选择唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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