How to iterate over rows in Pandas Dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Let’s see the how to iterate over rows in Pandas Dataframe using inerrows() and itertuples() :
Method #1: Using the DataFrame.iterrows() method
This method iterated over the rows as (index, series) pairs.
# importing pandas import pandas as pd # list of dicts input_df = [{'name':'Sujeet', 'age':10}, {'name':'Sameer', 'age':11}, {'name':'Sumit', 'age':12}] df = pd.DataFrame(input_df) print('Original DataFrame: \n', df) print('\nRows iterated using iterrows() : ') for index, row in df.iterrows(): print(row['name'], row['age']) |
Original DataFrame:
age name
0 10 Sujeet
1 11 Sameer
2 12 Sumit
Rows iterated using iterrows() :
Sujeet 10
Sameer 11
Sumit 12
Method #2: Using the DataFrame.itertuples() method
This method returns a named tuple for every row. getattr() function can be used to get the row attribute in the returned tuple. This method is faster than Method #1.
# importing pandas import pandas as pd # list of dicts input_df = [{'name':'Sujeet', 'age':10}, {'name':'Sameer', 'age':110}, {'name':'Sumit', 'age':120}] df = pd.DataFrame(input_df) print('Original DataFrame: \n', df) print('\nRows iterated using itertuples() : ') for row in df.itertuples(): print(getattr(row, 'name'), getattr(row, 'age')) |
Original DataFrame:
age name
0 10 Sujeet
1 110 Sameer
2 120 Sumit
Rows iterated using itertuples() :
Sujeet 10
Sameer 110
Sumit 120
There are few other ways we can iterate over rows in Pandas Dataframe. See Different ways to iterate over rows in Pandas Dataframe.
Recommended Posts:
- Different ways to iterate over rows in Pandas Dataframe
- Sorting rows in pandas DataFrame
- Ranking Rows of Pandas DataFrame
- Get all rows in a Pandas DataFrame containing given substring
- Dealing with Rows and Columns in Pandas DataFrame
- How to randomly select rows from Pandas DataFrame
- Create a list from rows in Pandas DataFrame | Set 2
- Create a list from rows in Pandas dataframe
- Iterating over rows and columns in Pandas DataFrame
- How to get rows/index names in Pandas dataframe
- Selecting rows in pandas DataFrame based on conditions
- Python | Delete rows/columns from DataFrame using Pandas.drop()
- Python | Pandas DataFrame.fillna() to replace Null values in dataframe
- Drop rows from the dataframe based on certain condition applied on a column
- Grouping Rows in pandas
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



