How to Solve Python AttributeError: ‘Series’ object has no attribute ‘iterrows’

by | Programming, Python, Tips

n Python, a Pandas Series is a one-dimensional labelled array capable of holding data of any type. Pandas Series is the same as a column in an Excel spreadsheet. You cannot iterate over a Series object using iterrows(). If you try to call iterrows() on a Series, you will raise the AttributeError: ‘Series’ object has no attribute ‘iterrows’. To solve this error, call the iterrows() method on the DataFrame object you want to iterate over instead of the Series, for example, for i, row in dataframe.iterrows():. Alternatively, you can call iteritems() on the Series, for example, for i, value in series.iteritems():

This tutorial will go over the error in detail and how to solve it with code examples.


AttributeError: ‘Series’ object has no attribute ‘iterrows’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘Series’ object has no attribute ‘iterrows’” tells us that the Series object we are handling does not have the iterrows attribute. The iterrows() method generates an iterator object of a DataFrame, allowing us to iterate over each row in the DataFrame. The syntax for iterrows is as follows.

dataframe.iterrows()

Parameters

The iterrows() method takes no parameters.

Returns

An iterator with two objects for each row: the index and the content as a Series object.

Example

Let’s look at an example where we want to iterate over a two-column DataFrame. The first column contains a letter of the alphabet and the second column contains random numbers between 0 and 1000.

import numpy as np

import pandas as pd

np.random.seed(0)

df = pd.DataFrame({'Col1':list('abcdefg'), 'Col2':np.random.choice(1000, 7)})

print(df)
  Col1  Col2
0    a   684
1    b   559
2    c   629
3    d   192
4    e   835
5    f   763
6    g   707

Next, we will try to iterate over the rows in Col2 and check if each number is a multiple of two, and if it is, we print the entire row to the console.

for idx, row in df['Col2'].iterrows():

    if row % 2 == 0:

        print(row)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-02dd77199b5e> in <module>
----> 1 for idx, row in df['Col2'].iterrows():
      2     if row % 2 == 0:
      3         print(row)
      4 

~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5581         ):
   5582             return self[name]
-> 5583         return object.__getattribute__(self, name)
   5584 
   5585     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'iterrows'

We get an AttributeError because df['Col2'] is a Series object, not a DataFrame. We can only call iterrows() on a DataFrame.

Solution #1: Use iterrows

To solve this error, we need to call iterrows() on the DataFrame df, which involves removing the ['Col2'] index. Let’s look at the revised code:

for idx, row in df.iterrows():

    if row['Col2'] % 2 == 0:

        print(row['Col1'], row['Col2'])

Let’s run the code to get the result:

a 684
d 192

We successfully found the values in Col2 that are multiples of two and printed the rows that they belong.

Solution #2: Use iteritems()

We can also use the Series method iteritems() to iterate over the values in a Series object. In this case, we want to call the iteritems() on the column we want to iterate over. Let’s look at the revised code:

for idx, num in df['Col2'].iteritems():

   if num % 2 == 0:
   
       print(df['Col1'][idx], num)

The iteritems() method returns an iterable tuple of (index, value). We check if the value in the Col2 Series is a multiple of 2 and print the values of Col1 and Col2 at that index. Let’s run the code to see the result:

a 684
d 192

We get the same result as the iterrows implementation.

Summary

Congratulations on reading to the end of this tutorial! The AttributeError ‘Series’ object has no attribute ‘iterrows’ occurs when you try to call the iterrows() method on a Series instead of a DataFrame. To solve this error, you can either call the iterrows() method on the DataFrame or call iteritems() on the Series.

For further reading on Series, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨