Checking if the list of string starts with tuple returning None in pandas

Viewed 22

I am trying to check if list within a pandas dataframe starts with string from separate list of string. However, I keep getting None. Here is what I tried:

import pandas as pd
frame = pd.DataFrame({'a' : ['111,222,2333,444', '211,44', '222,333,444','666,777','555']})
frame['place_holder']=frame['a'].apply(lambda x:((x.upper()).split(',')))
codes = ['55', '33']

def value_check(x,codes):

    if any(str(item).startswith(tuple(codes)) for item in x):
        return True

frame.apply(lambda x: value_check(frame['place_holder'],codes),axis=1)

I get None in all rows I should get True in 3rd row and 5th row.

Thanks,

Sam

1 Answers

You're calling apply wrong: your lambda does not use x at all. Try:

frame['place_holder'].apply(value_check, codes=codes)

On another note, you can forget the place holder and chain all the commands:

(frame['a'].str.upper().str.split(',').explode()
  .str.startswith(tuple(codes))
  .groupby(level=0).any()
)

Output:

0    False
1    False
2     True
3    False
4     True
Name: a, dtype: bool
Related