python-3.x 将panda Dataframe 每行中的列表与特定列表进行比较,并输出到单独的panda Dataframe 列

xhv8bpkk  于 2023-03-20  发布在  Python
关注(0)|答案(3)|浏览(116)

我有一个名为fruit_list的列表

[apple,orange,pineapple,banana,tomato]

我想将这个列表与名为fruits的panda Dataframe 列进行匹配,并输出交集。
以及一个列名为fruits的pandas Dataframe

fruits
[apple,mango]
[mango,cabbage,pineapple,carrot]
[egg,sandwich,orange,carrot,tomato]

预期产出

output      
[apple]
[pineapple]
[orange,tomato]

如何有效地完成这一点的任何想法。谢谢!

prdp8dxp

prdp8dxp1#

map带过滤功能,我认为这是一个有效的解决方案

df['fruits'].map(lambda s: [x for x in s if x in fruit_list])
0             [apple]
1         [pineapple]
2    [orange, tomato]
Name: fruits, dtype: object
xzabzqsa

xzabzqsa2#

您可以使用apply并定义function

def in_fruits(row, lst):
    ret_lst = []
    for f in row:
        if f in lst:
            ret_lst.append(f)
    return ret_lst

interest_fruits = ['apple','orange','pineapple','banana','tomato']
df1 = pd.DataFrame({'Fruits':[['apple', 'mango'], ['mango', 'cabbage', 'pineapple', 'carrot'], ['egg', 'sandwich', 'orange', 'carrot', 'tomato']]})
df1.Fruits.apply(lambda x: in_fruits(x, interest_fruits))

它返回以下内容:

0             [apple]
1         [pineapple]
2    [orange, tomato]
Name: Fruits, dtype: object
qoefvg9y

qoefvg9y3#

使用set.intersection获取常见水果

df.fruits.apply(lambda x: list(set(x) & set(fruit_list)))

输出为

0             [apple]
1         [pineapple]
2    [orange, tomato]
Name: fruits, dtype: object

相关问题