python - 使用 itertuples 遍历 pandas dataframe

标签 python pandas

我正在使用 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 取代了丑陋的计数器结构

关于python - 使用 itertuples 遍历 pandas dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43221208/

相关文章:

python - Zebra 打印机忽略该命令

python - 在具有多个 if 语句的 Pandas Lambda 函数中使用 Apply

python - 对 Pandas DataFrame 中存在非数字值的所有列求和

python - 从 Pandas 数据框中过滤只有零的列

python - 对多索引 Pandas 数据框上的重复行求和

python - 如何修复Python中的 "UnicodeEncodeError: ' ascii'编解码器无法编码字符u'\xa 0' in position 3656: ordinal not in range(128)"错误

python - 使用 pybind11 将 c++ 函数添加到现有 python 模块

python - 如何向分词器添加关键字?

python - TensorFlow 与 IPython 不能很好地配合

pandas 过滤器值计数有多个答案