【问题标题】:Looking for words in string that matches the values in a dictionary, then return key in a new column在字符串中查找与字典中的值匹配的单词,然后在新列中返回键
【发布时间】:2018-09-10 10:12:06
【问题描述】:

我一直在尝试遍历 pandas 数据框中的字符串以查找特定的单词集,在这里我成功了。

但是,我意识到我不仅要查找单词,还要查看单词的语义并将一组与我的主要关键字具有相同含义的单词组合在一起。

我偶然发现了以下问题 How to return key if a given string matches the keys value in a dictionary,这正是我想要做的,但不幸的是无法让它在 pandas 数据框中工作。

以下是可以在链接中找到的解决方案之一:

my_dict = {"color": ("red", "blue", "green"), "someothercolor":("orange", "blue", "white")}

solutions = []

my_color = 'blue'

for key, value in my_dict.items():
    if my_color in value:
        solutions.append(key)

输出:

color

我的数据框:

现在我有一个数据框,我想遍历 df['Name'] 以找到一个值,然后我想将键添加到新列。在此示例中,它将是 df['Colour']

+---+----------+--------------------------+-----------------------------+----------+--------+
|   |   SKU    |           Name           |         Description         | Category | Colour |
+---+----------+--------------------------+-----------------------------+----------+--------+
| 0 | 7E+10    | Red Lace Midi Dress      | Red Lace Midi D...          | Dresses  |        |
| 1 | 7E+10    | Long Armed Sweater Azure | Long Armed Sweater Azure... | Sweaters |        |
| 2 | 2,01E+08 | High Top Ruby Sneakers   | High Top Ruby Sneakers...   | Shoes    |        |
| 3 | 4,87E+10 | Tight Indigo Jeans       | Tight Indigo Jeans...       | Denim    |        |
| 4 | 2,2E+09  | T-Shirt Navy             | T-Shirt Navy...             | T-Shirts |        |
+---+----------+--------------------------+-----------------------------+----------+--------+

预期结果:

+---+----------+--------------------------+-----------------------------+----------+--------+
|   |   SKU    |           Name           |         Description         | Category | Colour |
+---+----------+--------------------------+-----------------------------+----------+--------+
| 0 | 7E+10    | Red Lace Midi Dress      | Red Lace Midi D...          | Dresses  | red    |
| 1 | 7E+10    | Long Armed Sweater Azure | Long Armed Sweater Azure... | Sweaters | blue   |
| 2 | 2,01E+08 | High Top Ruby Sneakers   | High Top Ruby Sneakers...   | Shoes    | red    |
| 3 | 4,87E+10 | Tight Indigo Jeans       | Tight Indigo Jeans...       | Denim    | blue   |
| 4 | 2,2E+09  | T-Shirt Navy             | T-Shirt Navy...             | T-Shirts | blue   |
+---+----------+--------------------------+-----------------------------+----------+--------+

我的代码:

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

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

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

我收到以下错误:

TypeError: 'in <string>' requires string as left operand, not tuple

我无法针对字符串运行元组。我该如何处理?

【问题讨论】:

    标签: python pandas string dataframe dictionary


    【解决方案1】:

    您需要遍历字典键元组值中的每个值。

    根据错误消息,您无法检查 tuple 是否存在于 str 类型中。

    此外,请确保您的 else 语句出现在外部 for 循环之后,以便在输出默认值之前测试所有键。

    最后,请确保您检查与str.lower(),因为字符串匹配在 Python 中是区分大小写的。

    import pandas as pd
    
    df = pd.DataFrame({'Name': ['Red Lace Midi Dress', 'Long Armed Sweater Azure',
                                'High Top Ruby Sneakers', 'Tight Indigo Jeans',
                                'T-Shirt Navy']})
    
    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 Lace Midi Dress    red
    1  Long Armed Sweater Azure   blue
    2    High Top Ruby Sneakers    red
    3        Tight Indigo Jeans   blue
    4              T-Shirt Navy   blue
    

    【讨论】:

    • 非常感谢您的详尽解释,它可以作为例外。假设我有多个与 df['Name'] 列匹配的值。示例:蓝色和红色蕾丝中长连衣裙。将这些存储在同一个单元格中是否容易? (蓝色,红色)。
    • 有可能。我建议你自己去。如果遇到困难,可以单独提出问题。
    【解决方案2】:

    您正在尝试在字符串中搜索单词的元组,而我想您想检查该元组的任何单词是否在字符串中。

    BTW 字符串在 python 中区分大小写。

    你可以替换:

    if value in x: 
    

    if any(word in x.lower() for word in value):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2021-08-18
      • 2017-03-22
      • 1970-01-01
      • 2020-08-04
      相关资源
      最近更新 更多