python - 查找包含特定字符的字符串的单元格数量

标签 python pandas

我想知道每行中有多少单元格包含具有特定字符的字符串。例如:

d = {'a':[1,2,'abc','ace'],'b':['aa','bb','cc',5],'c':['zzz','byy','xxx','wwb']}
df = pd.DataFrame(d, index=['m','n','o','p'])
df

    a   b   c
m   1   aa  zzz
n   2   bb  byy
o   abc cc  xxx
p   ace 5   wwb

我想知道每行中包含“b”的单元格数量:

    a   b   c   Count
m   1   aa  zzz 0
n   2   bb  byy 2
o   abc cc  xxx 1
p   ace 5   wwb 1

str.contains 适用于 Series,不适用于 DataFrame。我可以单步执行索引并执行类似的操作

df.loc['m','Count'] = df.loc['m'].str.contains('b').sum()

但似乎应该有一个我现在缺少的更简单的解决方案。

最佳答案

更新:

In [60]: df.apply(lambda x: x.str.contains('b')).sum(1)
Out[60]:
m    0.0
n    2.0
o    1.0
p    1.0
dtype: float64

In [57]: df.apply(lambda x: x.str.contains('b').sum(), axis=1)
Out[57]:
m    0
n    2
o    1
p    1
dtype: int64

计算每行有多少个 b:

In [50]: df.astype(str).sum(axis=1).str.count('b')
Out[50]:
m    0
n    3
o    1
p    1
dtype: int64

关于python - 查找包含特定字符的字符串的单元格数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43899187/

相关文章:

python - 将我的 IP 地址连接到 flask 服务器时出错 - ubuntu ipython

python - 从 CSV 文件创建图形并使用 Django 和 Pandas Python 库呈现到浏览器

Python - Pandas 数据操作来计算基尼系数

python - 对列表中的每个项目重复整个 df

python - 显示给定 id 的单元格的信息

python - 使用 PANDAS 组合数据框并添加文件名

python - 如何告诉 tox 不要从依赖项收集测试?

python - 索引值 16 的 list.index(value) 的值设置为 9

python - Matplotlib 绘图窗口出现在不同的桌面上

python - 为什么 Twisted Transports 没有接收数据的方法?