【问题标题】:Removing multiple substrings in a pandas dataframe column删除熊猫数据框列中的多个子字符串
【发布时间】:2019-03-14 13:56:16
【问题描述】:

我在 pandas 数据框中有一列成分。我需要删除除成分名称之外的所有内容(例如:1/3 杯腰果 > 腰果)。

输入

    recipe_name                                ingredient
0   Truvani Chocolate Turmeric Caramel Cups    ⅓ cup cashews
1   Truvani Chocolate Turmeric Caramel Cups    4 dates
2   Truvani Chocolate Turmeric Caramel Cups    1 tablespoon almond butter
3   Truvani Chocolate Turmeric Caramel Cups    3 tablespoons coconut milk
4   Truvani Chocolate Turmeric Caramel Cups    ½ teaspoon vanilla extract

预期输出

    recipe_name                                ingredient
0   Truvani Chocolate Turmeric Caramel Cups    cashews
1   Truvani Chocolate Turmeric Caramel Cups    dates
2   Truvani Chocolate Turmeric Caramel Cups    almond butter
3   Truvani Chocolate Turmeric Caramel Cups    coconut milk
4   Truvani Chocolate Turmeric Caramel Cups    vanilla extract 

我尝试过使用字典,常用词映射到空字符串,如下所示:

remove_list ={'\d+': '', 'ounces': '', 'ounce': '', 'tablespoons': '', 'tablespoon': '', 'teaspoons': '', 'teaspoon': '', 'cup': '', 'cups': ''}
column = df['ingredient']
column.apply(lambda column: [remove_list[y] if y in remove_list else y for y in column])

这根本没有改变数据。

我也尝试过使用正则表达式:

df['ingredients'] = re.sub(r'|'.join(map(re.escape, remove_list)), '', df['ingredients'])

但这只会给出错误提示“TypeError:预期的字符串或缓冲区。”

我对 Python 很陌生,所以我认为使用正则表达式是可能的,我只是不知道该怎么做。

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    由于您想用相同的字符替换所有内容,只需将它们放入列表中即可。

    l = ['\d+', '[^\x00-\x80]+', 'ounces', 'ounce', 'tablespoons', 
         'tablespoon', 'teaspoons', 'teaspoon', 'cup', 'cups']
    

    然后使用一个replace,加入一切。

    df.ingredient.str.replace('|'.join(l), '', regex=True).str.strip()
    # Safer to only replace stand-alone words. strip not needed
    #df.ingredient.str.replace('|'.join([x + '\s' for x in l]), '', regex=True)
    

    输出:

    0            cashews
    1              dates
    2      almond butter
    3       coconut milk
    4    vanilla extract
    Name: ingredient, dtype: object
    

    我将'[^\x00-\x80]+' 添加到列表中以删除那些小数字符,.str.strip 删除替换后的任何多余或前导空格。

    【讨论】:

    • @Conor 请小心,因为这会意外地将 5 cupcakes 替换为 cakes。您可以通过替换'\cup\s' 来解决这个问题,这样它只会在后面跟着空格时替换单词,如'cup ' 而不是'cupc'
    • 啊,谢谢,我刚刚回来查看,因为我遇到了这个问题。
    • @ALollz 我怎样才能修改它,以便它只会在后面没有任何内容时替换单词,即字符串结尾?
    【解决方案2】:

    为此,pandas 数据帧中内置了一组字符串函数。

    这样的事情应该可以工作:

    df['ingredient'] = df['ingredient'].str.replace('\d+', '', regex=True)
    

    我不知道你是否可以使用字典,你可能需要遍历你的字典来获得你想要的所有替换。

    for ptn, rpl in remove_list.items():
        df['ingredient'] = df['ingredient'].str.replace(ptn, rpl, regex=True)
    

    【讨论】:

    • 我试图在不为每个单词使用单独的替换语句的情况下做到这一点,但这可能是唯一的方法
    • 您可以使用您必须通过多行代码(如上)遍历模式的 dict。
    【解决方案3】:

    您可以使用循环和.split() 方法:

    i = 0
    for row in df['ingredient']:
        item = row.split(sep=' ', maxsplit=1)
        df['ingredient'].loc[i] = item[1]
        i += 1
    

    输出将是:

        recipe_name                                ingredient
    0   Truvani Chocolate Turmeric Caramel Cups    cup cashews
    1   Truvani Chocolate Turmeric Caramel Cups    dates
    2   Truvani Chocolate Turmeric Caramel Cups    tablespoon almond butter
    3   Truvani Chocolate Turmeric Caramel Cups    tablespoons coconut milk
    4   Truvani Chocolate Turmeric Caramel Cups    teaspoon vanilla extract
    

    如果您想保留测量值,您可以创建一个重复的列,在其中一列中保留值,在另一列中保留成分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-27
      • 2018-03-23
      • 2021-08-12
      • 2016-07-30
      • 2019-03-06
      • 2018-10-25
      • 2019-01-17
      • 2023-01-11
      相关资源
      最近更新 更多