Python 二维矩阵上的 Numpy where()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24219841/
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
Numpy where() on a 2D matrix
提问by Delta_Fore
I have a matrix like this
我有一个这样的矩阵
t = np.array([[1,2,3,'foo'],
[2,3,4,'bar'],
[5,6,7,'hello'],
[8,9,1,'bar']])
I want to get the indices where the rows contain the string 'bar'
我想获取行包含字符串“bar”的索引
In a 1d array
在一维数组中
rows = np.where(t == 'bar')
should give me the indices [0,3] followed by broadcasting:-
应该给我指数 [0,3] 然后是广播:-
results = t[rows]
should give me the right rows
应该给我正确的行
But I can't figure out how to get it to work with 2d arrays.
但我不知道如何让它与二维数组一起工作。
采纳答案by Jaime
For the general case, where your search string can be in any column, you can do this:
对于一般情况,您的搜索字符串可以位于任何列中,您可以执行以下操作:
>>> rows, cols = np.where(t == 'bar')
>>> t[rows]
array([['2', '3', '4', 'bar'],
['8', '9', '1', 'bar']],
dtype='|S11')
回答by Delta_Fore
You have to slice the array to the col you want to index:
您必须将数组切片到要索引的列:
rows = np.where(t[:,3] == 'bar')
result = t1[rows]
This returns:
这将返回:
[[2,3,4,'bar'],
[8,9,1,'bar']]