python – iterate over pandas dataframe using itertuples

python – iterate over pandas dataframe using itertuples

When using itertuples you get a named tuple for every row. By default, you can access the index value for that row with row.Index.

If the index value isnt what you were looking for then you can use enumerate

for i, row in enumerate(df.itertuples(), 1):
    print(i, row.name)

enumerate takes the place of an ugly counter construct

for row in df.itertuples():
    print(getattr(row, Index), getattr(row, name))

python – iterate over pandas dataframe using itertuples

For column names that arent valid Python names, use:

for i, row in enumerate(df.itertuples(index=False)):
    print(str(i) + row[df.columns.get_loc(My nasty - column / name)])

If you dont specify index=False, the column before the one named will be read.

Leave a Reply

Your email address will not be published.