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.

Asked By: Lynn

||

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
Answered By: sammywemmy
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.