Pandas DataFrame - Iterate over Rows

Kontext Kontext 0 233 0.21 index 6/14/2022

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:

01 A1  2 B2  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
pandas python

Join the Discussion

View or add your thoughts below

Comments