在Python中统计Pandas DataFrame中出现的单词的数量可以通过以下步骤实现:
import pandas as pd
import re
df = pd.DataFrame({'text': ['Hello world', 'This is a test', 'Hello again']})
def count_words(text):
words = re.findall(r'\w+', text.lower())
return len(words)
df['word_count'] = df['text'].apply(count_words)
print(df)
这将输出以下结果:
text word_count
0 Hello world 2
1 This is a test 4
2 Hello again 2
在这个例子中,我们使用了正则表达式来匹配单词,并将其转换为小写。然后,我们使用apply
函数将count_words
函数应用到DataFrame的每一行,并将结果存储在新的列word_count
中。
推荐的腾讯云相关产品:腾讯云服务器(CVM)和腾讯云数据库(TencentDB)。
领取专属 10元无门槛券
手把手带您无忧上云