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
-
Can you explain the output of your two last rows please?Corralien– Corralien2021-10-21 15:37:51 +00:00Commented 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 fruitRaklet57– Raklet572021-10-21 15:42:20 +00:00Commented 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 itseek– seek2021-10-21 15:44:55 +00:00Commented Oct 21, 2021 at 15:44
-
@Raklet57 absolutely you are correct it should pick like thatseek– seek2021-10-21 15:46:06 +00:00Commented Oct 21, 2021 at 15:46
-
any help @Corralien from your endseek– seek2021-10-21 15:54:09 +00:00Commented Oct 21, 2021 at 15:54
|
Show 1 more comment
1 Answer
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
1 Comment
seek
excellent working thanks for help
