【发布时间】: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 很陌生,所以我认为使用正则表达式是可能的,我只是不知道该怎么做。
【问题讨论】: