如何使用NumPy数组索引从2D数组中选择2列以从中选择唯一值? [英] How can I use NumPy array indexing to select 2 columns out of a 2D array to select unique values from?
问题描述
这可能是一个非常愚蠢的问题,但是我已经搜索了并且无法在任何地方找到答案(可能是因为它太愚蠢了).
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
数组.我想在1st
或2nd
列中标识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屋!