简体   繁体   English

Numpy在2D矩阵上的where()

[英]Numpy where() on a 2D matrix

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 在1d数组中

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. 但我无法弄清楚如何让它与2d数组一起工作。

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')

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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM