How to iterate over the first n rows of a pandas DataFrame in python ?


Examples of how to iterate over the first n rows of a pandas DataFrame in python

Create a pandas dataframe

Let's first create a DataFrame:

import pandas as pd
import numpy as np

data = np.arange(1,31)
data = data.reshape(10,3)

df = pd.DataFrame(data, columns=['A','B','C'])

print(df)

gives

    A   B   C
0   1   2   3
1   4   5   6
2   7   8   9
3  10  11  12
4  13  14  15
5  16  17  18
6  19  20  21
7  22  23  24
8  25  26  27
9  28  29  30

Iterate over the first n rows using head()

A first solution is to use the pandas head() method:

n = 4

df.head(n)

will display here the first 4 rows:

    A   B   C
0   1   2   3
1   4   5   6
2   7   8   9
3  10  11  12

Using iloc()

A second approach is to use iloc()

df.iloc[:n,:]

gives

    A   B   C
0   1   2   3
1   4   5   6
2   7   8   9
3  10  11  12

Using iterrows()

Another possible solution is to use iterrows()

for index,row in df.iterrows():
    if index < n:
        print(row)
        print()

A    1
B    2
C    3
Name: 0, dtype: int64

A    4
B    5
C    6
Name: 1, dtype: int64

A    7
B    8
C    9
Name: 2, dtype: int64

A    10
B    11
C    12
Name: 3, dtype: int64