创建一个计算“;”的新列

2024-04-19 19:50:07 发布

您现在位置: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

Tags: innone示例fordata数量ifis
1条回答
网友
1楼 · 发布于 2024-04-19 19:50:07

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

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的行,因为它保留了所有行的运行总计,而这不是您所要求的。我留着它以防万一那是你想要的。你知道吗

相关问题 更多 >