Python 字符串上的 Numpy 'where'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16642022/
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 string
提问by Rohit
I would like to use the numpy.where function on a string array. However, I am unsuccessful in doing so. Can someone please help me figure this out?
我想在字符串数组上使用 numpy.where 函数。但是,我这样做是不成功的。有人可以帮我解决这个问题吗?
For example, when I use numpy.whereon the following example I get an error:
例如,当我numpy.where在以下示例中使用时,出现错误:
import numpy as np
A = ['apple', 'orange', 'apple', 'banana']
arr_index = np.where(A == 'apple',1,0)
I get the following:
我得到以下信息:
>>> arr_index
array(0)
>>> print A[arr_index]
>>> apple
However, I would like to know the indices in the string array, Awhere the string 'apple'matches. In the above string this happens at 0 and 2. However, the np.whereonly returns 0 and not 2.
但是,我想知道字符串数组A中字符串'apple'匹配的索引。在上面的字符串中,这发生在 0 和 2 处。但是,np.where唯一返回的是 0 而不是 2。
So, how do I make numpy.wherework on strings? Thanks in advance.
那么,我如何numpy.where处理字符串?提前致谢。
采纳答案by Joran Beasley
print a[arr_index]
not array_index!!
不是array_index!!
a = np.array(['apple', 'orange', 'apple', 'banana'])
arr_index = np.where(a == 'apple')
print arr_index
print a[arr_index]

