Skip to main content
 首页 » 编程设计

python之如何计算列中的值

2024年11月24日9birdshome

我有一个名为 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.