如何使用pandas iterrows()获得当前迭代的计数?

时间:2019-03-31 02:51:04

标签: python pandas dataframe

我正在尝试遍历DataFrame,但是通过index查看时得到的iterrows()是DataFrame中的索引。相反,我希望它是0123 ...

        for ind, row in last_10.iterrows():
            print('ind', ind)

这将返回:

2345
2346
2347
...

我希望它是

0
1
2
...

2 个答案:

答案 0 :(得分:2)

使用enumerate

for ind, row in enumerate(last_10.iterrows()):
    print('ind', ind)
    print('data',row[1]['columns'])

range创建

for ind in range(len(last_10)):
    print('ind', ind)
    print('data',df.iloc[ind]['columns'])

答案 1 :(得分:1)

    from itertools import tee 


    import pandas as pd
    df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])

    def pair_iterate(iter):
        first, second = tee(iter)
        next(second, None)
        return zip(first, second)

    for (i1, row1), (i2, row2) in pair_iterate(df.iterrows()):
        print(i1, i2, row1["value"], row2["value"])