'Retrieving the value of the row where the "time" value is 1 less for each row

For each row, I need to find the row which is before 1 period(time column) and retrieve the value. To solve this, For loop is too slow... Is there any way to apply vector calculation for this? Or is there another way to speed up?

#making df
import pandas as pd
df = pd.DataFrame({'ID':[100001, 100002, 100003, 100004, 100005],
                'name':['Kim', 'Lee', 'Jeong', 'Park', 'Han'],
                'class':['H', 'W', 'S', "P", 'D'],
                'time':[1,2, 3, 4, 5],
               'value':[1111, 2222, 3333, 4444, 5555]
              })

Retrieving the value of the row where the "time" value is 1 less for each row : using for iteration

for i in range(0, len(df)):
    ID_row = df.at[i, 'ID']
    row_time = df.loc[df['ID']==ID_row]['time'].values[0]
    try:
        df.loc[df['ID']==ID_row, 'before_1'] = df.loc[df['time']==(row_time-1)]['value'].values[0]
    except:
        df.loc[df['ID']==ID_row, 'before_1'] = 0

Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source