gpt4 book ai didi

python - 计算 Pandas 数据框中每个特定单词的出现次数

转载 作者:太空狗 更新时间:2023-10-29 17:26:38 24 4
gpt4 key购买 nike

我想计算数据框中每个特定单词的出现次数。我目前使用 str.contains:

a = df2[df2['col1'].str.contains("sample")].groupby('col2').size()
n = a.apply(lambda x: 1).sum()

有没有一种方法可以匹配正则表达式并获取出现次数?在我的例子中,我有一个大数据框,我想匹配大约 100 个字符串。

最佳答案

更新:原始答案计算那些包含子字符串的行。

要计算一个子字符串的所有出现次数,您可以使用 .str.count :

In [21]: df = pd.DataFrame(['hello', 'world', 'hehe'], columns=['words'])

In [22]: df.words.str.count("he|wo")
Out[22]:
0 1
1 1
2 2
Name: words, dtype: int64

In [23]: df.words.str.count("he|wo").sum()
Out[23]: 4

str.contains 方法接受正则表达式:

Definition: df.words.str.contains(self, pat, case=True, flags=0, na=nan)
Docstring:
Check whether given pattern is contained in each string in the array

Parameters
----------
pat : string
Character sequence or regular expression
case : boolean, default True
If True, case sensitive
flags : int, default 0 (no flags)
re module flags, e.g. re.IGNORECASE
na : default NaN, fill value for missing values.

例如:

In [11]: df = pd.DataFrame(['hello', 'world'], columns=['words'])

In [12]: df
Out[12]:
words
0 hello
1 world

In [13]: df.words.str.contains(r'[hw]')
Out[13]:
0 True
1 True
Name: words, dtype: bool

In [14]: df.words.str.contains(r'he|wo')
Out[14]:
0 True
1 True
Name: words, dtype: bool

要计算出现的次数,您可以对这个 bool 系列求和:

In [15]: df.words.str.contains(r'he|wo').sum()
Out[15]: 2

In [16]: df.words.str.contains(r'he').sum()
Out[16]: 1

关于python - 计算 Pandas 数据框中每个特定单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17573814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com