Iterate over first N rows in pandas

Hasn't anyone answered the simple solution?

for row in df.head(5).itertuples():
    # do something

Take a peek at this post.


I know others have suggested iterrows but no-one has yet suggested using iloc combined with iterrows. This will allow you to select whichever rows you want by row number:

for i, row in df.iloc[:101].iterrows():
    print(row)

Though as others have noted if speed is essential an apply function or a vectorized function would probably be better.

>>> df
     a    b
0  1.0  5.0
1  2.0  4.0
2  3.0  3.0
3  4.0  2.0
4  5.0  1.0
5  6.0  NaN
>>> for i, row in df.iloc[:3].iterrows():
...     print(row)
... 
a    1.0
b    5.0
Name: 0, dtype: float64
a    2.0
b    4.0
Name: 1, dtype: float64
a    3.0
b    3.0
Name: 2, dtype: float64
>>>

Tags:

Python

Pandas