0

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

Community
  • 1
  • 1
Monirrad
  • 465
  • 1
  • 7
  • 17
  • https://stackoverflow.com/questions/23664877/pandas-equivalent-of-oracle-lead-lag-function – H_J Dec 22 '18 at 05:33
  • Possible duplicate of [Pandas equivalent of Oracle Lead/Lag function](https://stackoverflow.com/questions/23664877/pandas-equivalent-of-oracle-lead-lag-function) – Prayson W. Daniel Dec 22 '18 at 06:41

1 Answers1

2

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

Jonno_FTW
  • 8,601
  • 7
  • 58
  • 90