删除熊猫数据框列中的多个子字符串

Con*_*nor 5 python regex 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
Run Code Online (Sandbox Code Playgroud)

预期产出

    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 
Run Code Online (Sandbox Code Playgroud)

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

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])
Run Code Online (Sandbox Code Playgroud)

这根本没有改变数据。

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

df['ingredients'] = re.sub(r'|'.join(map(re.escape, remove_list)), '', df['ingredients'])
Run Code Online (Sandbox Code Playgroud)

但这只是给出了一个错误,说“类型错误:预期的字符串或缓冲区”。

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

ALo*_*llz 8

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

l = ['\d+', '[^\x00-\x80]+', 'ounces', 'ounce', 'tablespoons', 
     'tablespoon', 'teaspoons', 'teaspoon', 'cup', 'cups']
Run Code Online (Sandbox Code Playgroud)

然后使用一个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)
Run Code Online (Sandbox Code Playgroud)

输出:

0            cashews
1              dates
2      almond butter
3       coconut milk
4    vanilla extract
Name: ingredient, dtype: object
Run Code Online (Sandbox Code Playgroud)

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