How to get the index of numpy string array?

Question:

The numpy array is of strings and when I use

 a = np.where(arr==yourelement)[0]

It gives me a future warning
that is

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

What is this caused by?
Is this caused by the strings or something else???

arr is a string array like:
arr = np.array["alex","james","andy"]
yourelement is one of the elements chosen from the array arr
And now I want to know the index of yourelement in arr

Asked By: Hydra_Ali

||

Answers:

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. 
Answered By: medium-dimensional
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.