SoFunction
Updated on 2024-11-19

Summary of methods for iterating over DataFrame rows in Pandas

Python is a great language for data analysis, mainly because of the wonderful ecosystem of data-centric Python packages.Pandas is one of them, which makes importing and analyzing data much easier.

1. Using the index attribute of Dataframe

# import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit',
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce',
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = (data, columns=['Name', 'Age', 
                                 'Stream', 'Percentage'])
print("Given Dataframe :\n", df)
print("\nIterating over rows using index attribute :\n")
# iterate through each row and select
# 'Name' and 'Stream' column respectively.
for ind in :
    print(df['Name'][ind], df['Stream'][ind])

exports

Given Dataframe :
         Name  Age    Stream  Percentage
0      Ankit   21      Math          88
1       Amit   19  Commerce          92
2  Aishwarya   20      Arts          95
3   Priyanka   18   Biology          70
Iterating over rows using index attribute :
Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology

2. Use of DataFrame locs

# import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit',
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce',
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = (data, columns=['Name', 'Age',
                                 'Stream', 
                                 'Percentage'])
print("Given Dataframe :\n", df)
print("\nIterating over rows using loc function :\n")
# iterate through each row and select
# 'Name' and 'Age' column respectively.
for i in range(len(df)):
    print([i, "Name"], [i, "Age"])

exports

Given Dataframe :
         Name  Age    Stream  Percentage
0      Ankit   21      Math          88
1       Amit   19  Commerce          92
2  Aishwarya   20      Arts          95
3   Priyanka   18   Biology          70
Iterating over rows using loc function :
Ankit 21
Amit 19
Aishwarya 20
Priyanka 18

3. iloc using DataFrame

# import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce', 
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = (data, columns=['Name', 'Age',
                                 'Stream', 'Percentage'])
print("Given Dataframe :\n", df)
print("\nIterating over rows using iloc function :\n")
# iterate through each row and select
# 0th and 2nd index column respectively.
for i in range(len(df)):
    print([i, 0], [i, 2])

exports

Given Dataframe :
         Name  Age    Stream  Percentage
0      Ankit   21      Math          88
1       Amit   19  Commerce          92
2  Aishwarya   20      Arts          95
3   Priyanka   18   Biology          70
Iterating over rows using iloc function :
Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology

4. Using Dataframe's iterrows()

# import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce',
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = (data, columns=['Name', 'Age', 
                                 'Stream', 'Percentage'])
print("Given Dataframe :\n", df)
print("\nIterating over rows using iterrows() method :\n")
# iterate through each row and select
# 'Name' and 'Age' column respectively.
for index, row in ():
    print(row["Name"], row["Age"])

exports

Given Dataframe :
         Name  Age    Stream  Percentage
0      Ankit   21      Math          88
1       Amit   19  Commerce          92
2  Aishwarya   20      Arts          95
3   Priyanka   18   Biology          70
Iterating over rows using iterrows() method :
Ankit 21
Amit 19
Aishwarya 20
Priyanka 18

5. Using Dataframe's itertuples()

# import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 'Aishwarya',
                 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce', 'Arts', 
                   'Biology'],
        'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = (data, columns=['Name', 'Age', 
                                 'Stream',
                                 'Percentage'])
print("Given Dataframe :\n", df)
print("\nIterating over rows using itertuples() method :\n")
# iterate through each row and select
# 'Name' and 'Percentage' column respectively.
for row in (index=True, name='Pandas'):
    print(getattr(row, "Name"), getattr(row, "Percentage"))

exports

Given Dataframe :
         Name  Age    Stream  Percentage
0      Ankit   21      Math          88
1       Amit   19  Commerce          92
2  Aishwarya   20      Arts          95
3   Priyanka   18   Biology          70
Iterating over rows using itertuples() method :
Ankit 88
Amit 92
Aishwarya 95
Priyanka 70

6. Using DataFrame's apply()

# import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 'Aishwarya',
                'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce', 'Arts',
                'Biology'],
        'Percentage': [88, 92, 95, 70]}
# Convert the dictionary into DataFrame
df = (data, columns=['Name', 'Age', 'Stream',
                                'Percentage'])print("Given Dataframe :\n", df)
print("\nIterating over rows using apply function :\n")
​​​​​​​# iterate through each row and concatenate
# 'Name' and 'Percentage' column respectively.
print((lambda row: row["Name"] + " " +
            str(row["Percentage"]), axis=1))

exports

Given Dataframe :
         Name  Age    Stream  Percentage
0      Ankit   21      Math          88
1       Amit   19  Commerce          92
2  Aishwarya   20      Arts          95
3   Priyanka   18   Biology          70
​​​​​​​Iterating over rows using apply function :
0        Ankit 88
1         Amit 92
2    Aishwarya 95
3     Priyanka 70
dtype: object

Above is a summary of the methods of iterating DataFrame rows in Pandas in detail, more information about Pandas Dataframe iterative rows please pay attention to my other related articles!