深度阅读

How to remove words from a list in pandas?

作者
作者
2023年08月22日
更新时间
10.34 分钟
阅读时间
0
阅读量

To remove words from a list in pandas, you can use the Series.str.replace() method. For example, let’s say you have a Pandas Series of strings containing the words you want to remove:

import pandas as pd

# Create a sample series
s = pd.Series(['apple', 'banana', 'cherry', 'date'])

# Create a list of words to remove
words_to_remove = ['banana', 'date']

# Remove the words from the series
s = s.str.replace('|'.join(words_to_remove), '')

The str.replace() method takes a regular expression pattern as its first argument. In this case, we join the words to remove with the “|” character, which represents “or” in regular expression syntax. This creates a pattern that will match any of the words to remove. The second argument to str.replace() is the replacement string, which we leave empty to remove the words.

After running this code, the Series s will contain the following values:

0     apple
1    cherry
dtype: object

Notice that the words “banana” and “date” have been removed from the list.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。