python - 删除 Pandas 数据框列中的多个子字符串

标签 python regex pandas

我在 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: expected string or buffer.”

我是 Python 的新手,所以我认为使用正则表达式是可行的,我只是不确定该怎么做。

最佳答案

既然你想用相同的字符替换所有的东西,就把它们放在一个列表中。

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 删除了任何多余的或前导的字符替换后的空格。

关于python - 删除 Pandas 数据框列中的多个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52726935/

相关文章:

python - 在 View 之间共享并在 AppConfig 中初始化的变量

python - 为什么此代码没有删除行? (Flask-SQLAlchemy)

Python 的正则表达式模块 : repeating 'backreferences' does not appear to work correctly

PHP:浏览器版本号 user-agent with Version/x.x.x (Safari & Opera)

python - KeyError : 'PNG' while using pytesseract. 图像到数据

regex - 如何让 "grep -zoP"分别显示每个匹配项?

c++ - 如何从 C++ 中的一串科学数字中删除后面的零

python - Pandas:通过对来自不同 df 的列求和来创建新 df 的 Pythonic 方式

python - 有没有办法打破带有类别的 pandas 列,以将类别名称作为列名称来分隔 true 或 false 列

python-3.x - 测试确切的字符串是否出现在 Pandas 系列中