Pandas DataFrame - Iterate over Rows

visibility 9 access_time 14 days ago languageEnglish timeline Stats
timeline Stats
Page index 0.60
more_horiz

It is not a good practice to iterate over rows in Pandas DataFrame as it is considered as anti-pattern. However, if you really have use cases to iterate through the DataFrame, for example, process rows sequentially, you can use the code snippet in this page. 

Use DataFrame.iteritems()

The following code snippet uses DataFrame.iteritems() function.

import pandas as pd

df = pd.DataFrame({'c1': [1, 2, 3], 'c2': ['A', 'B', 'C']})

for index, row in df.iterrows():
    c1 = row['c1']
    c2 = row['c2']
    print(index)
    print(c1, c2)

Output:

0
1 A
1  
2 B
2  
3 C

Use DataFrame.itertuples()

The following code snippet uses itertuples function.

import pandas as pd

df = pd.DataFrame({'c1': [1, 2, 3], 'c2': ['A', 'B', 'C']})

for tuple in df.itertuples():
    print(tuple)
    print(tuple.Index)
    print(tuple.c1, tuple.c2)

Output:

Pandas(Index=0, c1=1, c2='A')
0
1 A
Pandas(Index=1, c1=2, c2='B')
1
2 B
Pandas(Index=2, c1=3, c2='C')
2
3 C
info Last modified by Kontext 14 days ago copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

More from Kontext
Pandas DataFrame Plot - Line Chart
visibility 1,743
thumb_up 2
access_time 2 years ago
Pandas DataFrame Plot - Line Chart
Torchvision error: Could not find module image.pyd
visibility 3,191
thumb_up 4
access_time 7 months ago