如何根据文本中某些单词的结尾来计算文本的行数



我正在尝试计算我的数据帧中包含单词/字母'red'的行数,以某种形式作为一个单独的单词或单词的一部分。

df = pd.DataFrame({'id': [10, 46, 75, 12, 99],
'text': [['The blurred vision is no good'],         
['start', '15', 'tag', '#redding'],
[],
['The books were blue instead'],
['Red is the new Black ']
]
})

输出应该计数第0、1和4行,即count=3。

我尝试了以下代码:

df['text'].str.contains(r'[a-zA-Z]red+', na=False).sum()

但是它不起作用。如果有人能帮我修一下,我将非常感激。

一个选择是在列表推导中使用any来检查字符串"red"是否出现在子列表中的任何字符串中:

out = sum(any(True for x in lst if 'red' in x.lower()) for lst in df['text'])

输出:

3

因为在"text"列,我将首先用空格连接这些单独的字符串。

然后,将字符串小写以进行不区分大小写的匹配,最后对整个连接字符串使用contains。任何"红色"的出现;在一种形式的另一种形式将很容易过滤:

>>> df['text'].str.join(" ").str.lower().str.contains('red')
0     True
1     True
2    False
3    False
4     True
Name: text, dtype: bool

,对于行数:

>>> df['text'].str.join(" ").str.lower().str.contains('red').sum()
3

最新更新