我正在使用itertuples迭代遍历一个pandas数据框架。同时,我还想在迭代过程中捕获行号:
for row in df.itertuples():
print row['name']
预期输出:
1 larry
2 barry
3 michael
1、2、3是行号。我想避免使用计数器并获取行号。在Pandas中是否有一种容易的方法来实现这一点?
使用itertuples
时,您会为每一行获取一个命名的tuple
。默认情况下,您可以使用row.Index
访问该行的索引值。
如果索引值不是您要查找的内容,则可以使用enumerate
。
for i, row in enumerate(df.itertuples(), 1):
print(i, row.name)
enumerate
取代了一个丑陋的计数器结构
for row in df.itertuples():
print(getattr(row, 'Index'), getattr(row, 'name'))
row.Index
和row.name
不就可以了吗? - nurettin对于不是有效Python名称的列名,请使用:
for i, row in enumerate(df.itertuples(index=False)):
print(str(i) + row[df.columns.get_loc('My nasty - column / name')])
如果您没有指定index=False
,则将读取该列之前的列。get_loc
返回列的索引,而不是字符串。 - Chris
enumerate
在Python中是一种常见的模式,这似乎很奇怪。我会使用它。否则,df.reset_index()
将带来一个基于0的索引,因此行号将是您为给定行迭代的索引+1。 - Zeugmaiterrows
。 - Cheng