0

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

6
  • Can you explain the output of your two last rows please? Commented Oct 21, 2021 at 15:37
  • from what i see: if single fruit is in multiple fruits then output=single fruit || if single fruit is not in multiple fruits then output = one random fruit which is in multiples fruit Commented Oct 21, 2021 at 15:42
  • hey @Corralien if single_fruit col value is not matched with multiple_fruits col value the output should be pick from multiple_fruits col value either any of element from it Commented Oct 21, 2021 at 15:44
  • @Raklet57 absolutely you are correct it should pick like that Commented Oct 21, 2021 at 15:46
  • any help @Corralien from your end Commented Oct 21, 2021 at 15:54

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

excellent working thanks for help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.