Pandas DataFrame - Iterate over Rows
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 3 years ago
copyright
This page is subject to Site terms.
comment Comments
No comments yet.