Search code examples
pandasloopscalculated-columns

create column based on column values - loop over column


I would like to create a new column "Group". The integer values from column "Step_ID" should be converted in loop from 1 to 4. See the image below.

enter image description here

import pandas as pd  
data = {'Step_ID': [1, 1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11]}  
df1 = pd.DataFrame(data) 

Solution

  • TRY:

    df['Group'] = (df.Step_ID % 4).replace(0 ,4)
    

    OUTPUT:

        Step_ID  Group
    0         1      1
    1         1      1
    2         2      2
    3         2      2
    4         3      3
    5         4      4
    6         5      1
    7         6      2
    8         6      2
    9         7      3
    10        8      4
    11        8      4
    12        9      1
    13       10      2
    14       11      3
    15       11      3