Reputation: 1
I want to count the total occurrence of the number 5
in my dataframe df
with 4 lists inside it (there are 3 numbers 5
in my df
). But in my code bellow the if
statement stops when it encounters the first False
return and does not count the third 5
in the last list in df
. How I can resolve this?
df = [[1,3,5,7,9],[1,2,3,4,5],[2,4,6,8,10],[2,5,6,8,10]]
n,m,counter=0,5,0
for i in range(4):
if df[n].count(m):
print('ok')
counter=counter+1
n=n+1
else:
print('NO')
print(counter)
Upvotes: 0
Views: 473
Reputation: 124
I approached the problem a bit differently, but here is the code I would use to solve this problem:
df = [[1,3,5,7,9],[1,2,3,4,5],[2,4,6,8,10],[2,5,6,8,10]]
m=5
counter = 0
for sublist in df:
counter += sublist.count(m)
print(counter)
Rather than creating multiple variables and having a 'for loop', I set up a for loop to iterate through each list in the original list.
Upvotes: 1
Reputation: 340
You aren't getting to look at every list because you are only incrementing n
if you do find a '5' in the list. But you only try 4 times, so you are effectively looking at [2,4,6,8,10]
twice and then running out of range
.
Upvotes: 0
Reputation: 85512
You need to index with i
not with n
here:
if df[n].count(m):
Better:
if df[i].count(m):
Shorter way:
sum(x.count(5) for x in df)
Upvotes: 3