计算pandas数据帧中某些单词的出现次数

时间:2013-07-10 14:48:13

标签: python pandas dataframe

我想计算数据框中某些单词的出现次数。我知道使用“str.contains”

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

目前我正在使用上面的代码。有没有一种方法可以匹配正则表达式并获取出现次数?在我的情况下,我有一个大型数据帧,我想匹配大约100个字符串。

3 个答案:

答案 0 :(得分:16)

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

要计算子字符串的所有匹配项,您可以使用.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

要计算出现的次数,您可以将此布尔值系列加总:

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

答案 1 :(得分:4)

要计算匹配总数,请使用s.str.match(...).str.get(0).count()

如果你的正则表达式将匹配几个独特的单词,要单独计算,请使用 s.str.match(...).str.get(0).groupby(lambda x: x).count()

它的工作原理如下:

In [12]: s
Out[12]: 
0    ax
1    ay
2    bx
3    by
4    bz
dtype: object

match字符串方法处理正则表达式...

In [13]: s.str.match('(b[x-y]+)')
Out[13]: 
0       []
1       []
2    (bx,)
3    (by,)
4       []
dtype: object

......但结果如同给出的那样,不是很方便。字符串方法get将匹配作为字符串,并将空结果转换为NaN ...

In [14]: s.str.match('(b[x-y]+)').str.get(0)
Out[14]: 
0    NaN
1    NaN
2     bx
3     by
4    NaN
dtype: object

......不计算在内。

In [15]: s.str.match('(b[x-y]+)').str.get(0).count()
Out[15]: 2

答案 2 :(得分:0)

您可以使用 value_count 函数。

import pandas as pd

# URL to .csv file
data_url = 'https://vincentarelbundock.github.io/Rdatasets/csv/carData/Arrests.csv'
# Reading the data
df = pd.read_csv(data_url, index_col=0)

enter image description here

# pandas count distinct values in column
df['sex'].value_counts()

enter image description here

来源:link

相关问题