How would I execute a Pivot Wider in Pandas? (Python)
Question:
I have a dataset, df:
Action Date
Begin 3/16/2020 12:35:47 PM
End 3/16/2020 12:35:49 PM
Begin 3/16/2020 01:35:47 PM
End 3/16/2020 01:35:49 PM
Desired outcome:
Begin End
3/16/2020 12:35:47 PM 3/16/2020 12:35:49 PM
3/16/2020 01:35:47 PM 3/16/2020 01:35:49 PM
Structure:
Action Date
Begin 3/16/2020 12:35
End 3/16/2020 12:35
Begin 3/16/2020 13:35
End 3/16/2020 13:35
I think this is a permute type problem, but not exactly sure. I have tried:
df2=df.pivot(columns='Action', values='Date')
This gives strange NAN values
df1 = df.set_index(['Action','Date']).unstack().reset_index()
Any suggestion is helpful.
Answers:
You could use the pivot, and do a bfill on the End or a ffill on the Begin column :
(df.pivot(columns='Action',values='Date')
.assign(End = lambda x:x.End.bfill())
.dropna()
.rename_axis(None,axis='columns')
)
Begin End
0 3/16/2020 12:35:47 PM 3/16/2020 12:35:49 PM
2 3/16/2020 01:35:47 PM 3/16/2020 01:35:49 PM
I have a dataset, df:
Action Date
Begin 3/16/2020 12:35:47 PM
End 3/16/2020 12:35:49 PM
Begin 3/16/2020 01:35:47 PM
End 3/16/2020 01:35:49 PM
Desired outcome:
Begin End
3/16/2020 12:35:47 PM 3/16/2020 12:35:49 PM
3/16/2020 01:35:47 PM 3/16/2020 01:35:49 PM
Structure:
Action Date
Begin 3/16/2020 12:35
End 3/16/2020 12:35
Begin 3/16/2020 13:35
End 3/16/2020 13:35
I think this is a permute type problem, but not exactly sure. I have tried:
df2=df.pivot(columns='Action', values='Date')
This gives strange NAN values
df1 = df.set_index(['Action','Date']).unstack().reset_index()
Any suggestion is helpful.
You could use the pivot, and do a bfill on the End or a ffill on the Begin column :
(df.pivot(columns='Action',values='Date')
.assign(End = lambda x:x.End.bfill())
.dropna()
.rename_axis(None,axis='columns')
)
Begin End
0 3/16/2020 12:35:47 PM 3/16/2020 12:35:49 PM
2 3/16/2020 01:35:47 PM 3/16/2020 01:35:49 PM