Pandas Tutorial Pandas References

Pandas DataFrame - itertuples() function



The Pandas DataFrame itertuples() function is used to iterate over the DataFrame rows as namedtuples.

Syntax

DataFrame.itertuples(index=True, name='Pandas')

Parameters

index Optional. If True, returns the index as the first element of the tuple. Default: True.
name Optional. Specify the name of the returned namedtuples or None to return regular tuples. Default is 'Pandas'.

Return Value

Returns an object to iterate over namedtuples for each row in the DataFrame with the first field possibly being the index and following fields being the column values.

Example: itertuples() example

The example below demonstrates the usage of itertuples() function.

import pandas as pd
import numpy as np

info = pd.DataFrame({
  "Salary": [25, 24, 30],
  "Bonus": [10, 8, 9],
  "Others": [5, 4, 7]},
  index= ["2015", "2016", "2017"]
)

print("The DataFrame contains:")
print(info,"\n")

for row in info.itertuples():
  print(row)

The output of the above code will be:

The DataFrame contains:
      Salary  Bonus  Others
2015      25     10       5
2016      24      8       4
2017      30      9       7 

Pandas(Index='2015', Salary=25, Bonus=10, Others=5)
Pandas(Index='2016', Salary=24, Bonus=8, Others=4)
Pandas(Index='2017', Salary=30, Bonus=9, Others=7)

Example: using index and name parameter

To remove the index as the first element of the tuple, the index parameter can set to False. Along with this, the name parameter can be used to set a custom name for the yielded namedtuples. Consider the example below:

import pandas as pd
import numpy as np

info = pd.DataFrame({
  "Salary": [25, 24, 30],
  "Bonus": [10, 8, 9],
  "Others": [5, 4, 7]},
  index= ["2015", "2016", "2017"]
)

print("The DataFrame contains:")
print(info,"\n")

#removes index as first element
for row in info.itertuples(index=False):
  print(row)

print()
#creates custom named namedtuples
for row in info.itertuples(name='FY'):
  print(row)

print()
#Using None as name parameter
for row in info.itertuples(name=None):
  print(row)  

The output of the above code will be:

The DataFrame contains:
      Salary  Bonus  Others
2015      25     10       5
2016      24      8       4
2017      30      9       7 

Pandas(Salary=25, Bonus=10, Others=5)
Pandas(Salary=24, Bonus=8, Others=4)
Pandas(Salary=30, Bonus=9, Others=7)

FY(Index='2015', Salary=25, Bonus=10, Others=5)
FY(Index='2016', Salary=24, Bonus=8, Others=4)
FY(Index='2017', Salary=30, Bonus=9, Others=7)

('2015', 25, 10, 5)
('2016', 24, 8, 4)
('2017', 30, 9, 7)

❮ Pandas DataFrame - Functions

5