0

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)
4
  • you're not iterating properly. instead of using for i in range(4) use something like this: Commented Apr 15, 2016 at 21:14
  • 1
    for l in df: for item in l: if item==5: print('ok') counter += 1 else: print('NO') print counter Commented Apr 15, 2016 at 21:14
  • 2
    Your df is not a dataframe. Commented Apr 15, 2016 at 21:15
  • Thanks n1c9!! "Learning, and perhaps even helping others!" I understandig, I had to do two iterations. My final code is: for l in df: for item in l: if item == m: counter += 1 print counter Commented Apr 16, 2016 at 12:05

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Mike Müller! Your shorter way is a very good solution!
1

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.

1 Comment

Thanks Apero! Your approach is another interesting way to do that.
0

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.

1 Comment

Thanks Sam! You are right, I understood my mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.