Home > other >  using pandas dataframe compare one column value with other list of elements in another column
using pandas dataframe compare one column value with other list of elements in another column

Time:10-22

using pandas compare two columns and create a new column if both columns match the same string else assign any value from a list of elements

enter image description here

CodePudding user response:

Check if single fruit is in multiple fruits then return single fruit else choose a random fruit in multiple fruits:

import numpy as np

df['output'] = df.apply(lambda x: x['single fruit'] 
                          if x['single fruit'] in x['multiple fruits']
                          else np.random.choice(x['multiple fruits']), axis=1)

Output:

>>> df
  single fruit              multiple fruits      output
0        apple               [apple, mango]       apple
1       grapes                     [grapes]      grapes
2   strawberry  [strawberry, grapes, mango]  strawberry
3    pineapple               [apple, mango]       apple
4        graps          [strawberry, mango]  strawberry
  • Related