Search code examples
pythondataframecell

How to fill the cell (i,j) with the cell (i-1,j-1) in a DataFram in Python


At first, I wanna apologize for my wording since I was not sure how to ask my question. Suppose that I have a dataframe as follows

'T' 'Y' 'item' 'item_p'

A | 2001 | 2 | Nan

A | 2002 | 3 | Nan

A | 2003 | 5 | Nan

A | 2004 | 6 | Nan

A | 2005 | 7 | Nan

B | 2001 | 9 | Nan

B | 2002 | 3 | Nan

B | 2003 | 5 | Nan

B | 2004 | 6 | Nan

B | 2005 | 7 | Nan

I want each cell in the column 'item_p' be filled with the value of the previous value of the column 'item'

So the result must be as bellow:

'T' 'Y' 'item' 'item_p'

A | 2001 | 2 | Nan

A | 2002 | 3 | 2

A | 2003 | 5 | 3

A | 2004 | 6 | 5

A | 2005 | 7 | 6

B | 2001 | 9 | 7

B | 2002 | 3 | 9

B | 2003 | 5 | 3

B | 2004 | 6 | 5

B | 2005 | 7 | 6

I have done the task with a nested for loops but I think there is some better way to do it. Is there any command to do such a task


Solution

  • Use df.shift()

    In your example:

    df['item_p'] = df['item'].shift(1)
    

    https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html