Find Values in a Pandas Series
Understand how to use find and any in a Pandas series.
We'll cover the following
Try it yourself
Try executing the code below to see the result.
import pandas as pdheros = pd.Series(['Batman', 'Wonder Woman', 'Superman'])if heros.str.find('Iron Man').any():print('Wrong universe')else:print('DC')
Python’s str.find
documentation says the following:
“Return the lowest index in the string where substring
sub
is found within the slices[start:end]
. Optional argumentsstart
andend
are interpreted as in slice notation. Return-1
ifsub
is not found.”
str1 = "Hello world"print(str1.find("world")) #returns 6 as w is located at index 6print(str1.find("hey")) #returns -1 as it doesn't exist in the string
In the Rectified puzzle, we saw that except for zeros, the Boolean
values of all numbers are True
.
When you run this code below, the pandas.Series.any
method will return True
if at least one of the values in the series is True
:
In [1]: heros.str.find('Iron Man')
Out[1]:
0 -1
1 -1
2 -1
dtype: int64
Since we have -1
as values, any
will return True
.
One way to solve this is to use the ==
operator:
In [2]: (heros == 'Iron Man').any()
Out[2]: False
Solution
import pandas as pdheros = pd.Series(['Batman', 'Wonder Woman', 'Superman'])if (heros == 'Iron Man').any():print('Wrong universe')else:print('DC')
Get hands-on with 1300+ tech skills courses.