社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Ntwanano • 3 年前 • 1328 次点击  

我需要创建一个新列来计算前导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
 
1328 次点击  
文章 [ 4 ]  |  最新文章 3 年前
Corralien
Reply   •   1 楼
Corralien    3 年前

尝试 str.findall :

df['0s'] = df['Sequence'].str.findall('^0*').str[0].str.len()
print(df)

# Output:
    Sequence  0s
0  012312312   1
1  024624624   1
2  036901357   1
3  002486248   2
4  045074305   1
5  080666140   1
enke
Reply   •   2 楼
enke    3 年前

IIUC,你想数一数前导0的数量,对吗?利用这样一个事实:当整数为 type str 转换为 type int .这里有一个解决方案:

df['leading 0s'] = df['Sequence'].str.len() - df['Sequence'].astype(int).astype(str).str.len()

输出:

    Sequence  leading 0s
0  012312312           1
1  024624624           1
2  036901357           1
3  002486248           2
4  045074305           1
5  080666140           1
Andreas
Reply   •   3 楼
Andreas    3 年前

你可以使用这个正则表达式:

'^0+'

这个 ^ 也就是说,如果模式从字符串的开头开始,则捕获。 这个 + 如果至少发生一次或多次,则表示捕获。

sammywemmy mozway
Reply   •   4 楼
sammywemmy mozway    3 年前

你可以用 extract ^(0*) 正则表达式只匹配前导零。然后使用 str.len 要知道长度。

df['0s'] = df['sequence'].str.extract('^(0*)', expand = False).str.len()

输入示例:

df = pd.DataFrame({'sequence': ['12040', '01230', '00010', '00120']})

输出:

  sequence  0s
0    12040   0
1    01230   1
2    00010   3
3    00120   2