如果给定的字符串与字典中的keys值匹配,如何返回字符串中的多个键

2024-06-01 12:07:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遍历一个dataframe列来提取一组特定的单词。我将这些映射为字典中的键值对,并在一些帮助下设置了每行的键。你知道吗

现在,我想做的是返回同一行中的多个键,如果值存在于字符串中,这些值应该用|(管道)分隔。你知道吗

代码:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Name': ['Red and Blue Lace Midi Dress', 'Long Armed Sweater Azure and Ruby',
                            'High Top Ruby Sneakers', 'Tight Indigo Jeans',
                            'T-Shirt Navy and Rose']})

colour = {'red': ('red', 'rose', 'ruby'), 'blue': ('azure', 'indigo', 'navy')}

def fetchColours(x):
    for key, values in colour.items():
        for value in values:
            if value in x.lower():
                return key
    else:
        return np.nan

df['Colour'] = df['Name'].apply(fetchColours)

输出:

        Name                            Colour
0       Red and Blue Lace Midi Dress    red
1  Long Armed Sweater Azure and Ruby    blue
2    High Top Ruby Sneakers             red
3        Tight Indigo Jeans             blue
4              T-Shirt Navy and Rose    blue

预期结果:

        Name                                 Colour
0       Red and Blue Lace Midi Dress         red
1       Long Armed Sweater Azure and Ruby    blue|red
2       High Top Ruby Sneakers               red
3       Tight Indigo Jeans                   blue
4       T-Shirt Navy and Rose                blue|red

Tags: andnamedfblueredazurelongmidi
2条回答

这个怎么样:

def fetchColors(x):
    color_keys = []
    for key, values in color.items():
        for value in values:
            if value in x.lower():
                color_keys.append(key)
    if color_keys:
        return '|'.join(color_keys)
    else:
        return np.nan

问题是,在找到键后直接返回,而应继续搜索,直到找到所有结果:

def fetchColours(x):
    keys = []
    for key, values in colour.items():
        for value in values:
            if value in x.lower():
                keys.append(key)
    if len(keys) != 0:
        return '|'.join(keys)
    else:
        return np.nan   

要想让它起作用,你必须改变:

 colour = {'red': ('red', 'rose', 'ruby'), 'blue': ('azure', 'indigo', 'navy')}

 colour = {'red': ('red', 'rose', 'ruby'), 'blue': ('azure', 'blue','indigo', 'navy')}

因为否则它不会在每个句子中搜索术语“blue”,这意味着它不能在第一个示例中将这个键添加到列表中。你知道吗

相关问题 更多 >