Iterating over a pandas file frame using itertuples

I am iterating over a pandas data framework using itertuples. I also want to capture line No. iterations:

Code example:

for row in df.itertuples(): print row['name'] 

expected output:

 1 larry 2 barry 3 michael 

Here 1, 2, 3 is the line number. I want to avoid using a counter and getting a line number. Is there an easy way to achieve this using pandas?

+5
source share
1 answer

When using itertuples you get the name tuple for each row. By default, you can access the index value for this row using row.Index .

If the index value is not what you were looking for, you can use enumerate

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

enumerate replaces the ugly counter design

+8
source

Source: https://habr.com/ru/post/1266335/


All Articles