DataFrame can't be iterated through: getting following error: tuple indices must be integers or slices, not str

Viewed 4721

I've been trying to debug my code for the last 30 minutes to no avail, maybe you can help?

The error lies withing line 17, but I'm truly clueless to why it's happening.

So, I'm using a dictionary in order to store the data that my function is_nontrivial_reverse_number() returns, which is a boolean type. I iterate through it and insert all of the values from 0 to 1100.

I then insert my dictionary into a DataFrame with the pandas library.

Then I iterate through my dataFrame in order to retrieve the count of the values that are set to true.

But the problem is that row["nonTrivial"] doesn't seem to be working, even though I used the same function on a different dictionary and dataframe set.

import pandas as pd2

dic2 = {'nonTrivial': [is_nontrivial_reverse_number(x) for x in range(0, 1100)]}
dic2

df2 = pd2.DataFrame(dic2)
df2 = df2.set_index('nonTrivial')

#df2.head()
##df2.shape
#df.dtypes



for row in df2.iterrows():
    if (row["nonTrivial"]==True):
        n = n+1
print (n)

Expected result : n=2

what I get:

TypeError                                 Traceback (most recent call last)
<ipython-input-314-ce7c400929e6> in <module>
     15
     16 for row in df2.iterrows():
---> 17     if (row["nonTrivial"]==True):
     18         n = n+1
     19 print (n)

TypeError: tuple indices must be integers or slices, not str
3 Answers

Why noone mentioned that he can unpack the tuple in the for loop like

for index, row in df2.iterrows():
    if (row["nonTrivial"]==True):
        n = n+1
    print (n)

iterrow returns a tuple. If you need to access the index of the column you want, you can do it with:

for row in df2.iterrows():
    if (row[1][df.columns.get_loc('nonTrivial') == True):
        n = n+1

Just a comment, you don't need to loop the rows. You can just do:

n += (df2['nonTrivial']==True).sum()

Try:

for row in df2.iterrows():
   if (row[1]["nonTrivial"]==True):
         n = n+1
Related