Python 使用 itertuples 迭代 Pandas 数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43221208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iterate over pandas dataframe using itertuples
提问by Sun
I am iterating over a pandas dataframe using itertuples. I also want to capture the row number while iterating:
我正在使用 itertuples 迭代 Pandas 数据框。我还想在迭代时捕获行号:
for row in df.itertuples():
print row['name']
Expected output :
预期输出:
1 larry
2 barry
3 michael
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?
1、2、3 是行号。我想避免使用计数器并获取行号。有没有一种简单的方法可以使用熊猫来实现这一目标?
回答by piRSquared
When using itertuplesyou get a named tuplefor every row. By default, you can access the index value for that row with row.Index.
使用时,itertuples您会tuple为每一行命名。默认情况下,您可以使用 访问该行的索引值row.Index。
If the index value isn't what you were looking for then you can use enumerate
如果索引值不是您要查找的值,那么您可以使用 enumerate
for i, row in enumerate(df.itertuples(), 1):
print(i, row.name)
enumeratetakes the place of an ugly counter construct
enumerate取代了丑陋的反结构
回答by Ashok Kumar Pant
for row in df.itertuples():
print(getattr(row, 'Index'), getattr(row, 'name'))
回答by Chris
For column names that aren't valid Python names, use:
对于不是有效 Python 名称的列名称,请使用:
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.
如果不指定index=False,则将读取已命名的列之前的列。

