创建一个新列,其计数为“;”连续

时间:2019-01-10 22:13:48

标签: python

我有下表示例:

如何创建一个新的列来计算';'的数量在每一行中?

S Locations
2111 31672;0
2113 31965;0;;
2100 0;78464;1

我尝试了以下循环:

total = 0
countlocation =[]
for line in data:
    if line is None:
        numSlashes= 0
    else:
        numSlashes = line.count(';')
    total += numSlashes + 1
    countlocation.append(total)
    total = 0

1 个答案:

答案 0 :(得分:0)

仅从数据结构中假设“”(空白)是您的列定界符,现在您有两列。下面应添加第三列,其中包含分号总数:

total = 0
countlocation =[]
for line in data:
    if line is None:
        numSlashes= 0
    else:
        numSlashes = line.count(';')

    total += numSlashes + 1
    #countlocation.append(line + " " + total) #for total of all rows
    countlocation.append(line + " " + numSlashes) #for total of this row
    total = 0

请注意,我注释掉了使用total的行,因为它保留了所有行的运行总计,而这并不是您要的。我把它留着,以防万一你想要的。