Search code examples
pythonlistdataframeiterable

Iterate through pairs of items


Given:

df =

     x    y
0  1.0  1.1
1  2.0  1.0
2  2.0  2.0
3  1.5  3.0

output =

 [1.0, 1.1, 2.0, 1.0] 
 [2.0, 1.0, 2.0, 2.0] 
 [2.0, 2.0, 1.5, 3.0]  
 [1.5, 3.0, 1.0, 1.1]

I can´t do the last list. It should be the last and fist rows of my dataframe.


Solution

  • Here use a loop where all elements are connected np.hstack. In df.loc the necessary indices are given in square brackets (on the left). On the last iteration, the code ends up in the else block, use last and first index are served.

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame({'x': [1.0, 2.0, 2.0, 1.5], 'y': [1.1, 1.0, 2.0, 3.0]})
    
    hist = len(df)
    for i in range(0, hist):
        if i <= (hist - 2):
            print(np.hstack(df.loc[[i, i + 1], :].values))
        else:
            print(np.hstack(df.loc[[i, 0], :].values))
    

    Output

    [1.  1.1 2.  1. ]
    [2. 1. 2. 2.]
    [2.  2.  1.5 3. ]
    [1.5 3.  1.  1.1]