Search code examples
pythonpandasdataframepandas-groupbysklearn-pandas

How to iterate column values over the other column by pandas?


I want to use the values of the Z over the X column. But I want to work in this way: 0 index value of the Z column will be shifted to index 1 of the X column. I want to shift values from 1 to 100 index. For this task, I want to work with For-loop. How may I write the code?

I am using pandas/python

#Index X     Y    Z
#0   Non    Non  10
#1   Non    Non  20
#2   Non    Non  30
#3   Non    Non  40
#4   Non    Non  50
#5   Non    Non  60
#6   Non    Non  70
#7   Non    Non  80
#8   Non    Non  90
#9   Non    Non  100
#10  Non    Non  110

Solution

  •  df['X'] = df['Z'].shift(1)
    
          Index X       Y   Z
        0   0   NaN     NaN 10
        1   1   10.0    NaN 20
        2   2   20.0    NaN 30
        3   3   30.0    NaN 40
        4   4   40.0    NaN 50
        5   5   50.0    NaN 60
        6   6   60.0    NaN 70
        7   7   70.0    NaN 80
        8   8   80.0    NaN 90
        9   9   90.0    NaN 100
    

    Here is the updated version ( update for the Y as well ):

     df['X'] = df['Z'].shift(1)
     df['Y'] = df['Z'].shift(2)
    
    
       Index    X   Y      Z
    0   0    NaN    NaN    10
    1   1   10.0    NaN    20
    2   2   20.0    10.0    30
    3   3   30.0    20.0    40
    4   4   40.0    30.0    50
    5   5   50.0    40.0    60
    6   6   60.0    50.0    70
    7   7   70.0    60.0    80
    8   8   80.0    70.0    90
    9   9   90.0    80.0    100
    

    I am not able to understand why you are insisting on a for-loop solution for your requirement. Here it is:

    def update_X_Y(frame):
        for x in range(frame.shape[0]):
            frame.loc[x+1,'X'] = frame.loc[x,'Z']
            frame.loc[x+2,'Y'] = frame.loc[x,'Z']
    
    ## Calling the function:
    update_X_Y(df)
    

    I would not use for-loop.