I am trying to create new column feature from curr_value feature. Here, I want get the value from previous current value, using df.curr_value.shift(fill_value=-1)
I can get the previous value. How do apply shift to only unique 'uid' columns. For example, In below example, I want to apply shift to uniqie ID values. df[df['uid']==1].curr_value.shift(fill_value=-1)
Is there any other way in pandas so that I dont need to iterate unique uid values?
import pandas as pd
import numpy as np
events = np.array([[1, 1, 1],
[1, 2, 4],
[1, 3, 3],
[1, 3, 4],
[2, 1, 4],
[2, 2, 3]])
df=pd.DataFrame(data=events, columns=["uid", "eid", "curr_value"])
Yes we can do it with groupby
df['pre'] = df.groupby('uid')['curr_value'].shift(fill_value=-1)
Out[5]:
0 -1
1 1
2 4
3 3
4 -1
5 4
Name: curr_value, dtype: int32
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.