栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

计算熊猫数据框中某些单词的出现

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计算熊猫数据框中某些单词的出现

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

要计算子字符串的所有出现次数,可以使用

.str.count

In [21]: df = pd.Dataframe(['hello', 'world', 'hehe'], columns=['words'])In [22]: df.words.str.count("he|wo")Out[22]:0    11    12    2Name: words, dtype: int64In [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 arrayParameters----------pat : string    Character sequence or regular expressioncase : boolean, default True    If True, case sensitiveflags : int, default 0 (no flags)    re module flags, e.g. re.IGNORECASEna : default NaN, fill value for missing values.

例如:

In [11]: df = pd.Dataframe(['hello', 'world'], columns=['words'])In [12]: dfOut[12]:   words0  hello1  worldIn [13]: df.words.str.contains(r'[hw]')Out[13]:0    True1    TrueName: words, dtype: boolIn [14]: df.words.str.contains(r'he|wo')Out[14]:0    True1    TrueName: words, dtype: bool

要计算出现的次数,您可以对布尔系列求和:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651149.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号