Python Pandas 过滤和分组

标签 python csv pandas

我将其作为 csv 在 pandas 中工作 - 前十行

print frame1.head(10)

      alert         Subject    filetype type      country   status
0  33965790    44676 aba     Attachment  doc  RU,RU,RU,RU  deleted
1  33965786    44676 rcrump  Attachment  zip          NaN  deleted
2  33965771            3aba  Attachment  zip          NaN  deleted
3  33965770             NaN  Attachment   js           ,,  deleted
4  33965766             NaN  Attachment   js           ,,  deleted
5  33965761             NaN  Attachment  zip          NaN  deleted
6  33965760             NaN  Attachment  zip          NaN  deleted
7  33965757             NaN  Attachment  zip          NaN  deleted
8  33965751  35200     3aba  Attachment  doc     RU,RU,RU  deleted
9  33965747  35200   INVaba  Attachment  zip          NaN  deleted

我需要获取主题列并计算以“aba”作为子字符串的所有行。

Occurrences of aba- 512

甚至是这样的结果

aba    12
3aba   5
INVaba 2

这是我的代码 -

targeted = frame1[frame1['Subject'].str.contains('aba', case=False , na=False)].groupby('Subject')
print (targeted.to_string(header=False))

收到错误 - AttributeError:无法访问“DataFrameGroupBy”对象的可调用属性“to_string”,请尝试使用“apply”方法

*****注意:我之前已经让它可以工作于不同文件类型的数量,这有效 -

filetype = frame1.groupby('filetype').size()
###clean up the printing
print "Delivered in Email"
print (filetype.to_string(header=False))

并给了我 -

Delivered in Email
Attachment    32647
Header          131
URL            9236

最佳答案

要获得完整计数,只需使用 str.contains接下来是 count

>>> df.Subject.str.contains('aba', case=False, na=False).count()
10

然后,要获取包含 'aba' 的唯一字符串的计数,您可以访问 contains 找到的值,然后使用 value_counts .

>>> df.loc[df.Subject.str.contains('aba', case=False, na=False), 'Subject'].value_counts()

3aba      1
INVaba    1
aba       1
Name: Subject, dtype: int64

关于Python Pandas 过滤和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42704927/

相关文章:

python - 是否可以构建一个具有过滤数据框的下拉菜单的绘图图?

python - 如何从单个列中获取多个列?

python - 如何通过 python 从 mediawiki 标记的文章中解析/提取数据

python - django 在生产环境中,urls.py 仅匹配空路径,即 ""而没有其他?

python - 使用 StreamingHttpResponse 流式传输和下载大型 CSV 文件

xml - 如何使用 XSLT 将 XML 转换为文本文件

Python - 将更改应用于整个列

python - Google OAuth2 - 如何更改 expires_in 或 token_expiry 值?

java - 有没有办法将多个参数发送到TestNG中的@Factory注释

python pandas 添加前导零以使所有月份均为 2 位数字