I am iterating over a pandas dataframe using itertuples. I also want to capture the row number while iterating:
for row in df.itertuples():
print row[\'name\
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 isn't 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 column names that aren't valid Python names, use:
for row in df.itertuples(index=False):
print(row[df.columns.get_loc('My nasty - column / name')])
If you don't specify index=False
, the column before the one named will be read.
for row in df.itertuples():
print(getattr(row, 'Index'), getattr(row, 'name'))