Pandas DataFrame - Iterate over Rows

visibility 34 event 2022-06-14 access_time 6 months ago language English
more_vert

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 6 months 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