使用itertuples遍历 pandas 数据框 [英] iterate over pandas dataframe using itertuples

查看:672
本文介绍了使用itertuples遍历 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用itertuples在熊猫数据框上进行迭代.我还想在迭代时捕获行号:

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']

预期输出:

1 larry
2 barry
3 michael

1、2、3是行号.我想避免使用计数器并获取行号.有没有简单的方法可以使用熊猫来实现这一目标?

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

推荐答案

使用itertuples时,每一行都会得到一个名为tuple的名称.默认情况下,您可以使用row.Index访问该行的索引值.

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.

如果索引值不是您想要的值,则可以使用enumerate

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代替了丑陋的计数器构造

enumerate takes the place of an ugly counter construct

这篇关于使用itertuples遍历 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆