iterrows pandas get next rows value

前端 未结 5 1058
南方客
南方客 2020-12-23 09:50

I have a df in pandas

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

I want to iterate over rows in

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 10:27

    Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.

    A version of your first idea that would work would be:

    row_iterator = df.iterrows()
    _, last = row_iterator.next()  # take first item from row_iterator
    for i, row in row_iterator:
        print(row['value'])
        print(last['value'])
        last = row
    

    The second method could do something similar, to save one index into the dataframe:

    last = df.irow(0)
    for i in range(1, df.shape[0]):
        print(last)
        print(df.irow(i))
        last = df.irow(i)
    

    When speed is critical you can always try both and time the code.

提交回复
热议问题