python - 如何计算列中的值

标签 python pandas count

我有一个名为 df 的数据框,我想计算 '|'和 '/' 分别在 name1 和 name2 中。

id name1    name2
1  a|b      a/b
2  a|b|c    a/b/c
3  a        a
4  a|b|c|d  a/b/c/d 

这是代码

[In] 1: import pandas as pd

        data = {'id' : pd.Series([1, 2, 3, 4]),
                'name1': pd.Series(['a|b', 'a|b|c', 'a', 'a|b|c|d']), 
                'name2': pd.Series(['a/b', 'a/b/c', 'a', 'a/b/c/d'])}
        df = pd.DataFrame(data)

[In] 2: df['name1'].str.count('|')
[Out] 2: 4
         6
         2
         8
[In] 3: df['name2'].str.count('/')
[Out] 3: 1
         2
         0
         3

我面临的问题是它为 3 提供了正确的输出,但为 2 提供了错误的输出。
注意:我想数“|”分开因为在原始数据中只有'|'这不是“/”。

最佳答案

问题是 | 是正则表达式的特殊字符,所以需要通过 \ 转义:

a = df['name1'].str.count('\|')
print (a)
0    1
1    2
2    0
3    3
Name: name1, dtype: int64

如果勾选Series.str.count :

Count occurrences of pattern in each string of the Series/Index.

This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the Series.

关于python - 如何计算列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57017933/

相关文章:

python - 在 Django 中,如何使用数据库时间保存或更新日期时间字段的日期时间?

python - 如何在 pandas 数据框中使用字符串列表作为条件

Mysql计算重复行的百分比

python - 想在 python 中获取主目录中的文件数

python - GPflow分类: interpretation of posterior variance

python - 在 Windows 8 中编译 mod_wsgi 不适用于 django

python - 替换 pandas 数据框列中的字符串

python - 使用 Matplotlib 绘制从 Pandas 中的 groupby 函数返回的数据

python - 一个数字在 numpy 数组中出现了多少次

c++ - 内存计数器 - 碰撞检测项目