Skip to content Skip to sidebar Skip to footer

Check If An Item In A List Is Available In A Column Which Is Of Type List

I'm trying to iterate over a list I have with a column in a dataframe which has list in each row. list1 = ['installing','install','installed','replaced','repair','repaired','replac

Solution 1:

you can do it apply and set like:

# I changed the list to the secondrowtoshow that the columnall works
list1 = ['daily', 'system', 'check', 'task',  'replace']
# create a setfrom it
s1 =set(list1)

# forany word, check that the intersectionof s1 
# and the setof the list in this rowisnotempty
df['col_any'] = df['lwr_nopunc_spc_nostpwrd'].apply(lambda x: any(set(x)&s1))

# forall, subtract the setof this rowfrom the set s1, 
# if notemptythen it returnTruewithany
# that you reverse using~in front of it togetTrue if all words from s1 arein this row
df['col_all'] =~df['lwr_nopunc_spc_nostpwrd'].apply(lambda x: any(s1-set(x)))
print (df)
                             lwr_nopunc_spc_nostpwrd  col_any  col_all
0                            [daily, ask, questions]     TrueFalse1              [daily, system, check, task, replace]     TrueTrue2  [inspection, complete, replaced, horizontal, s...    FalseFalse

Solution 2:

You could use some set arithmetic with list comprehensions, like this (note that I simplified your examples to have more obvious test cases):

import pandas as pd

list1 = ['installing', 'replace']
set1 = set(list1)

df = pd.DataFrame({'col1': [['daily', 'ask'], 
                            ['daily', 'replace'],
                            ['installing', 'replace', 'blade']]})

# new1 should be True when the intersection of list1 with the row from col1 is not empty
df['new1'] = [set1.intersection(set(row)) != set() for row in df.col1]

# new2 should be True when list1 is a subset of the row from col1 
df['new2'] = [set1.issubset(set(row)) for row in df.col1]

df
    col1                          new1   new2
0   [daily, ask]                  FalseFalse1   [daily, replace]              TrueFalse2   [installing, replace, blade]  TrueTrue

Post a Comment for "Check If An Item In A List Is Available In A Column Which Is Of Type List"