Home > Enterprise >  Check if item from a Pandas column list contains value from another column
Check if item from a Pandas column list contains value from another column

Time:09-23

Here is the DF,

df = pd.DataFrame({'List': ['[7%, 9%, 30%]', '[9%, 30%]', '[7%]'], 'Value' :  ['7%', '0%', '7%']})

List            Value
[7%, 9%, 30%]   7%
[9%, 30%]       0%
[7%]            7% 

How can I create a new column to check if value is in list column the expected output

List            Value  CTRL
[7%, 9%, 30%]   7%     True
[9%, 30%]       0%     False
[7%]            7%     True

Things tried without success..

df['CTRL'] = np.where([item for item in df['List']] == df['Value'], True, False)

CodePudding user response:

You need to loop here, a list comprehension should be the most efficient:

df['CTRL'] = [v in l.strip('[]').split(',')
              for l,v in zip(df['List'], df['Value'])]

Or, you you have lists (not strings as in the question):

df['CTRL'] = [v in l for l,v in zip(df['List'], df['Value'])]

output:

            List Value   CTRL
0  [7%, 9%, 30%]    7%   True
1      [9%, 30%]    0%  False
2           [7%]    7%   True
  • Related