Pandas iterrows TypeError: tuple indices must be integers or slices, not str
Have you tried to iterate over a DataFrame in Pandas, but got a TypeError: tuple indices must be integers or slices, not str ? If so, we’ll see what is the cause of the error and how to solve it.
1: Create simple DataFrame
To begin lets create simple DataFrame:
df = pd.DataFrame({'num_legs': [4, 2, 0], 'num_wings': [0, 2, 0]},
index=['dog', 'hawk', 'fish'])
data:
num_legs | num_wings | |
---|---|---|
dog | 4 | 0 |
hawk | 2 | 2 |
fish | 0 | 0 |
2: TypeError: tuple indices must be integers or slices, not str
If we like to iterate row by row and access the row data then we can use method: pandas.DataFrame.iterrows. A common problem for programmers is to not read docs(including me sometimes :) ) and go with solution like:
for row in df.iterrows():
print(row['num_wings'])
but this leads to the error which is the topic of the article:
TypeError: tuple indices must be integers or slices, not str
3: Solution for TypeError: tuple indices must be integers or slices, not str
Reading the docs of pandas.DataFrame.iterrows
we can find that:
Iterate over DataFrame rows as (index, Series) pairs.
which means that usage above is not correct. The correct code and the solution for TypeError: tuple indices is:
for index, row in df.iterrows():
full code:
for index, row in df.iterrows():
print(row['num_wings'])
now the result is:
0
2
0
4: Analyse similar errors like: TypeError: tuple indices must be integers or slices, not str
I've recommend to you to look at the error more carefully and find the problematic line:
TypeError Traceback (most recent call last)
<ipython-input-18-4ab72df7c78e> in <module>
1 for row in df.iterrows():
----> 2 print(row['num_wings'])
TypeError: tuple indices must be integers or slices, not str
then start removing or simplifying the line like:
print(row['num_wings'])
-> print(row)
and check what happens. Another way is by debugging and using evaluate expression. You can find more advanced techniques for debugging here: PyCharm - Breakpoints, Favorites, TODOs simple examples