【发布时间】:2022-01-24 02:12:40
【问题描述】:
我需要创建一个新列来计算前导 0 的数量,但是我在尝试这样做时遇到了错误。
我根据 mongo 上的以下正则表达式 [\^0[0]*[1-9][0-9]*\] 从 mongo 中提取数据并将其保存到 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。我可以将结果保存在列中以进行统计。
【问题讨论】: