1

checked:

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Iterate over pandas series

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iteritems.html

What I try to do is, based on a series value take different actions:

import pandas as pd
s = pd.Series([1,2,3, 4, 5, 6], name='number')
check_1 = ([1,2,3])
check_2 = ([4, 5, 6])
enter code here

different actions:

for index, value in s.items():
    if s.isin([check_1]).any():
        print('checked_1')
    elif s.isin([check_2]).any():
        print('checked_2')
    else:
        print ('nothing')

What I get is:

nothing --> *should be checked_1*  
nothing --> *should be checked_1*
nothing --> *should be checked_1*
nothing --> *should be checked_2*
nothing --> *should be checked_2*
nothing --> *should be checked_2*

2 Answers2

2

Here's how I would do it:

for index, value in s.items():
    if value in check_1:
        print('checked_1')
    elif value in check_2:
        print('checked_2')
    else:
        print ('nothing')
Hichame Yessou
  • 2,658
  • 2
  • 18
  • 30
2

Your code is not working because first of all you are keeping check_1 in square bracket i:e you are keeping a list in a square bracket. Even if you remove it, it will not work: it will give the result checked_1 all the time. Reason:

s.isin(check_1) #If you execute this it will return below:
    0     True
    1     True
    2     True
    3    False
    4    False
    5    False
    Name: number, dtype: bool

when you run .any() on the above output you will always get it True. Because .any returns True if any of the value is True, It will return False if all the values are false. Hence you will never go past the 'if' and will never reach the else block.

s.isin(check_1).any()
> True

As for answer I would have done the same hichame.yessou 's answer has done: hence not reposting.

instinct246
  • 960
  • 9
  • 15