簡體   English   中英

使用 Pandas 數據框將一列值與另一列中的其他元素列表進行比較

[英]using pandas dataframe compare one column value with other list of elements in another column

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

在此處輸入圖片說明

檢查single fruit是否在multiple fruits然后返回single fruit否則在multiple fruits隨機選擇一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM