Python - pandas: iterate over DataFrame with itertuples()

06 Jan 2018

Iterate over DataFrame rows as namedtuples, with index value as first element of the tuple

Arguments:

import pandas as pd

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")

df = df[['cars','mpg']]

df.head()
#                 cars       mpg
# 0          Mazda RX4  4.582576
# 1      Mazda RX4 Wag  4.582576

# for row in df.itertuples(index=True, name="Pandas"):
# same as:
for row in df.itertuples():
    print(str(row[0]) + " - " + str(row.cars) + " - " + str(row.mpg))
# 0 - Mazda RX4 - 4.58257569495584
# 1 - Mazda RX4 Wag - 4.58257569495584

for row in df.itertuples():
    print(type(row))
# <class 'pandas.core.frame.Pandas'>
# <class 'pandas.core.frame.Pandas'>

[ python  pandas  dataframe  ]