What is the pandas DataFrame.itertuples() method in Python?
Overview
The pandas package in Python is renowned for the efficient data manipulation of large datasets. Therefore, we are going to discuss the itertuples() function of the DataFrame class.
The DataFrame.itertuples() method returns an iterator object of DataFrame, returning each row as a Python tuple.
Syntax
DataFrame.itertuples(index=True, name='Pandas')
An example of DataFrame.itertuples()
Parameters
It takes the following argument values:
index: Boolean type, default isTrue- If it is set to
True, it returns the index as the first element of the tuple. name: The string orNonetype, the default value is'pandas'.- string: When set to
'pandas', it returns pandas named tuples. - None: When set to None, it returns regular tuples.
Return value
It returns an iterator of DataFrame, to iterate over the named tuples for each row.
Example
In the code snippet below, we are going to create an instance of DataFrame class and invoke itertuples() to extract each row of DataFrame as a tuple.
import pandas as pd# a data dictionarydata = {"Name": ["Sally", "Forgins", "Jhony", "Nourine"],"Designation": ["HR", "Software Engineer", "System Enginner", "Finance"],"Salary" :["$10,500","$12,000","$14,000","13,200"]}# creating DataFrame with default feature namesdf = pd.DataFrame(data)# iterate through each row# to get each row as a tuplefor row in df.itertuples():print(row)
Explanation
- Line 3: We create a dictionary containing the name, designation, and salaries of employees.
- Line 8: We use
pd.DataFrame()to create a data frame on the dictionary created above. - Line 11: We iterate through DataFrame rows and converting each row into a tuple by using
itertuples().