We can not create a numpy array using np.array["alex","james","andy"]
since it is an invalid syntax. np.array
is a function and thus, the correct way to create the desired numpy array is np.array(["alex","james","andy"])
.
Assuming that we create an array successfully using:
import numpy as np
x = np.array(["alex","james","andy"])
print(np.where(x == 3))
you are right - the comparison done with np.where
returns an error:
FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
This answer, as pointed out in the comment, will answer your question.
However, if you want to compare or find the index of an element which is of str
data type, you won't get any error:
print(np.where(x == "3"))
returns: (array([], dtype=int64),)
specifying that the data type of elements in the output object is int64
even though the array/output is empty.
To get the index of an element in the numpy array, you might want to use numpy.argwhere
. I have used yourelement
as "alex"
in this answer.
import numpy as np
x = np.array(["alex","james","andy"])
print(np.argwhere(x == "alex")[0][0]) # This gives 0 as an output.
Using np.argwhere
is helpful when you have more than one instance of an element in the list e.g.
y = np.array(["alex","james","andy", "alex"])
print(np.argwhere(y == "alex"))
gives: [[0] [3]]
Or you can convert x
to list using tolist
method and use index
method to get the index of yourelement
.
print(x.tolist().index("alex")) # This gives 0 as an output.