How To Make Previous And Next Columns In Dataframe From Existing Dataframe?
So, let's say I have a data frame like this. df = pd.DataFrame({'person':['A', 'A', 'B', 'B', 'A'], 'datetime':['2018-02-26 10:49:32', '2018-02-26 10:58:03', '20
Solution 1:
Use DataFrameGroupBy.shift
by 2 columns, and last remove last duplicated rows by person
column by Series.duplicated
with rename
columns:
df['datetime'] = pd.to_datetime(df['datetime'])
df1 = df.sort_values(by=['person', 'datetime'])
df1[['next_datetime','next_loc']] = df1.groupby('person')['datetime','location'].shift(-1)
d = {'datetime':'prev_datetime','location':'prev_loc'}
df2 = df1[df1['person'].duplicated(keep='last')].rename(columns=d)
print (df2)
person prev_datetime prev_loc next_datetime next_loc
4 A 2018-02-26 10:43:34 e 2018-02-26 10:49:32 a
0 A 2018-02-26 10:49:32 a 2018-02-26 10:58:03 b
2 B 2018-02-26 10:51:10 c 2018-02-26 10:58:45 d
Post a Comment for "How To Make Previous And Next Columns In Dataframe From Existing Dataframe?"