Python 根据两列的值选择numpy ndarray中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23359886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
selecting rows in numpy ndarray based on the value of two columns
提问by user3584444
I have a big np.ndarray (3600000,3)
, the HUE
, the VALUE
, and an associated CLASS
number. For each pairs of HUE
and VALUE
I would like to find, using this array the corresponding Class
number. I'm a very beginner in Python and have a hard time doing it. Do you know a way to do it?
我有一个 big np.ndarray (3600000,3)
、 the HUE
、 theVALUE
和一个关联的CLASS
数字。对于每个对HUE
和VALUE
我想找到,使用该阵列对应的Class
号码。我是 Python 的初学者,很难做到。你知道一种方法吗?
Thank you in advance!
先感谢您!
采纳答案by Kei Minagawa
I assume your array looks like:
我假设你的数组看起来像:
|(HUE)(VALUE)(CLASS)
row/col| 0 1 2
-------+-----------------
0 | 0 1 2
1 | 3 4 5
2 | 6 7 8
. | . . .
. | . . .
3599999| . . .
And here is the sample code. For simplicity I changed the size 3600000 to 5.
这是示例代码。为简单起见,我将大小 3600000 更改为 5。
a = np.array(xrange(5 * 3))
a.shape = (5, 3)
Now array a
look like this:
现在数组a
看起来像这样:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])
If you want row with HUE=9
, do like this:
如果你想用 排HUE=9
,这样做:
a[np.where(a[:,0] == 9)]
#array([[ 9, 10, 11]])
If you want row with VALUE=4
, do like this:
如果你想用 排VALUE=4
,这样做:
a[np.where(a[:,1] == 4)]
#array([[3, 4, 5]])
If you want row with HUE=0
and VALUE=1
, do like this:
如果你想用HUE=0
and排VALUE=1
,这样做:
a[np.where((a[:,0] == 0) * (a[:,1] == 1))]
#array([[0, 1, 2]])
回答by emeth
Try this code:
试试这个代码:
x[x[:, 2] == class_number[:, :2]
where x
is np.ndarray
这里x
是np.ndarray
x[:, 2] == class_number
contains true/false
that means whether the last is class_number
or not.
包含true/false
这意味着最后一个是否是class_number
。
You need to take a look at: Boolean indexing
in http://wiki.scipy.org/Cookbook/Indexing
你需要看看:Boolean indexing
在http://wiki.scipy.org/Cookbook/Indexing
Moved from comment.
从评论中移出。