'Shift values in one pandas df column down based on values of another column
I have a dataframe:
{
'Person': {
0: 1, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2,
7: 2, 8: 3, 9: 3, 10: 3, 11: 3
},
'Year': {
0: 2017, 1: 2018, 2: 2019, 3: 2020, 4: 2017, 5: 2018, 6: 2019,
7: 2020, 8: 2017, 9: 2018, 10: 2019, 11: 2020
},
'Value': {
0: 20, 1: 30, 2: 23, 3: 40, 4: 11, 5: 20, 6: 30,
7: 21, 8: 12, 9: 12, 10: 15, 11: 23
}
}
I want to shift Value column by 1 down row, but taking into account 'Author`.
I tried shift and roll, but did not get the necessary result.
Expected output:
{
'Person': {
0: 1, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2,
7: 2, 8: 3, 9: 3, 10: 3, 11: 3
},
'Year': {
0: 2017, 1: 2018, 2: 2019, 3: 2020, 4: 2017, 5: 2018, 6: 2019,
7: 2020, 8: 2017, 9: 2018, 10: 2019, 11: 2020
},
'Value': {
0: 20, 1: 30, 2: 23, 3: 40, 4: 11, 5: 20, 6: 30,
7: 21, 8: 12, 9: 12, 10: 15, 11: 23
},
'Value t-1': {
0: nan, 1: 20.0, 2: 30.0, 3: 23.0, 4: nan, 5: 11.0, 6: 20.0,
7: 30.0, 8: nan, 9: 12.0, 10: 12.0, 11: 15.0
}
}
Solution 1:[1]
Full credit goes to @enke
df['Value t-1'] = df.groupby('Person')['Value'].shift()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anakin Skywalker |
