循环不正常

时间:2017-02-14 00:17:34

标签: python loops pandas if-statement dataframe

使用数据框,这是我的代码。

numbers = 3
count=0
A = 0
B = 0 
C = 0
for x in range(numbers):
    if str(data.iloc[count])== 'A':
        A += 1 
    elif str(data.iloc[count])== 'B':
        B += 1 
    elif str(data.iloc[count])== 'C':
        C += 1 
count +=1
#this is to return the count to check if it works
print A
print B
print C

但由于某种原因,当我运行此代码时,只有A的计数增加。

即。如果索引中的数据有一个' B' B' B' B'它仍然返回A = 3和B = 0,它应该返回A = 1,B = 2,C = 0

我做错了什么?再次感谢。

2 个答案:

答案 0 :(得分:0)

由于count += 1不在for循环中,因此在for循环完成后,count + = 1仅运行一次。它需要缩进。或者,您不需要使用计数变量,因为x已经经过0到3的范围:

numbers = 3
A = 0
B = 0 
C = 0
for x in range(numbers):
    if str(data.iloc[x])== 'A':
        A += 1 
    elif str(data.iloc[x])== 'B':
        B += 1 
    elif str(data.iloc[x])== 'C':
        C += 1 

#this is to return the count to check if it works
print A
print B
print C

答案 1 :(得分:0)

这也有效

count=0
numbers = 3
A = 0
B = 0 
C = 0
for x in range(numbers):
    count +=1
    if str(data.iloc[x])== 'A':
        A += 1 
    elif str(data.iloc[x])== 'B':
        B += 1 
    elif str(data.iloc[x])== 'C':
        C += 1 

#this is to return the count to check if it works
print A
print B
print C