Del*_*ore 17 python arrays numpy matrix
我有一个像这样的矩阵
t = np.array([[1,2,3,'foo'],
[2,3,4,'bar'],
[5,6,7,'hello'],
[8,9,1,'bar']])
Run Code Online (Sandbox Code Playgroud)
我想得到行包含字符串'bar'的索引
在1d数组中
rows = np.where(t == 'bar')
Run Code Online (Sandbox Code Playgroud)
应该给我指数[0,3]然后广播: -
results = t[rows]
Run Code Online (Sandbox Code Playgroud)
应该给我正确的行
但我无法弄清楚如何让它与2d数组一起工作.
Del*_*ore 12
您必须将数组切片到要编制索引的列:
rows = np.where(t[:,3] == 'bar')
result = t1[rows]
Run Code Online (Sandbox Code Playgroud)
返回:
[[2,3,4,'bar'],
[8,9,1,'bar']]
Run Code Online (Sandbox Code Playgroud)
Jai*_*ime 12
对于一般情况,您的搜索字符串可以位于任何列中,您可以执行以下操作:
>>> rows, cols = np.where(t == 'bar')
>>> t[rows]
array([['2', '3', '4', 'bar'],
['8', '9', '1', 'bar']],
dtype='|S11')
Run Code Online (Sandbox Code Playgroud)