Py学习  »  Python

Python—计算行字符串上的连续前导数字,而不计算非连续数字

Ntwanano • 3 年前 • 1352 次点击  

我需要创建一个新列来计算前导0的数量,但是我在尝试这样做时会出错。 我根据以下正则表达式从mongo中提取数据 [\^0[0]*[1-9][0-9]*\] 并将其保存到csv文件中。这是所有以0开头的“序列”。

df['Sequence'].str.count('0')

df['Sequence'].str.count('0[0]*[1-9][0-9]')

给出以下结果。正如您所看到的,两个“count”字符串返回值也将计算非前导0。或者只是0的总数。

    Sequence    0s
0   012312312   1
1   024624624   1
2   036901357   2
3   002486248   2
4   045074305   3
5   080666140   3

我还尝试过使用循环编写代码,这在测试时有效,但在数据帧上使用时,我遇到了以下问题 **IndexError: string index out of range**

results = []
count = 0 
index = 0
for item in df['Sequence']:
    count = 0 
    index = 0
    while (item[index] == "0"):  
            count = count + 1          
            index = index + 1
    results.append(count)
df['0s'] = results
df

简言之如果我能用001230子串得到2而不是3。我可以将结果保存在一个列中,以便对其进行统计。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130917
 
1352 次点击  
文章 [ 4 ]  |  最新文章 3 年前