使用熊貓比較兩列,如果兩列匹配相同的字串,則創建一個新列,否則從元素串列中分配任何值

uj5u.com熱心網友回復:
檢查是否single fruit在multiple fruits然后回傳single fruit否則選擇一個隨機水果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)
輸出:
>>> 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331176.html
上一篇:加寬R資料框
下一篇:pandas使用方法鏈重命名列
