iterate over pandas dataframe using itertuples

前端 未结 3 1471
天命终不由人
天命终不由人 2021-02-03 23:33

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\         


        
3条回答
  •  一整个雨季
    2021-02-03 23:56

    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

提交回复
热议问题