iterrows pandas get next rows value

前端 未结 5 1063
南方客
南方客 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条回答
  •  萌比男神i
    2020-12-23 10:10

    There is a pairwise() function example in the itertools document:

    from itertools import tee, izip
    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return izip(a, b)
    
    import pandas as pd
    df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
    
    for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
        print i1, i2, row1["value"], row2["value"]
    

    Here is the output:

    0 1 AA BB
    1 2 BB CC
    

    But, I think iter rows in a DataFrame is slow, if you can explain what's the problem you want to solve, maybe I can suggest some better method.

提交回复
热议问题