First, let's see what the problem is, then we can find a way to fix it.
In [1]: import pandas as pd
In [2]: pets = pd.read_csv('pets.csv')
In [3]: pets
Out[3]:
Pets Owners
0 dog James
1 dog Katelyn
2 rat Shelly
3 cat Bob
In [4]: type(pets["Owners"])
Out[4]: pandas.core.series.Series
We can see that pets
is a pandas.Series
object. Now the problem is obviously in this line of code:
if owner in pets['Owners']:
Here's why you can't use in
operator with pandas.Series
, but basically, it's because the developers of Pandas
didn't implement this module in a way that would be possible to use "Membership test operations" like this. Therefore, as you mentioned yourself, this will always return False
:
In [5]: owner in pets["Owners"]
Out[5]: False
Now, if you want to use pets["Owners"]
you can do it like this (as suggested by @piRSquared):
In [6]: owner in pets["Owners"].values
Out[6]: True
However, if we look at the documentation for pandas.Series.values
:
Warning: We recommend using Series.array or Series.to_numpy(),
depending on whether you need a reference to the underlying data or a
NumPy array.
So we can do it like this:
In [7]: owner in pets["Owners"].array
Out[7]: True
There's also a better way of doing it, you want to find out if "there are any pets for a given owner," correct? If so, you can do it like this:
In [8]: pet = pets.loc[pets["Owners"] == owner, "Pets"]
In [8]: if pet.any():
...: print(pet)
...: else:
...: print("You didn't enter any Owner. Try again! ")
Out[8]:
1 dog
Name: Pets, dtype: object
As you can see, this will print a pandas.Series
object. You have mentioned that you need it in a "vector/list/array" format. It's a bit unclear, but I think the situation is that an owner
can have multiple pets
and you want to check if the owner
has any pets
, and then print all of their pets
in a list-type format. If so, you can use pet.array
. For example, if we modify your dataset so that Katelyn has more than one pet:
Pets Owners
dog James
dog Katelyn
rat Katelyn <-----
rat Shelly
cat Bob
Then we can see that it gives us a list:
In [9]: if pet.any():
...: print(pet.array)
...: else:
...: print("You didn't enter any Owner. Try again! ")
Out[9]:
<PandasArray>
['dog', 'rat']
Length: 2, dtype: object