Skip to content
Advertisement

Pandas – stack time columns with time and date

I have date and time data now I want to reduce this dataframe to two columns with Timestamp (date+time) in a column and value in another column

current df –

JavaScript

desired df –

JavaScript

Here is original list from which I’m creating my dataframe –

JavaScript

Advertisement

Answer

Use melt to flatten your dataframe and set Time as a name of the variable column. Combine columns Date and Time to create the timestamp then sort_values to reorder your dataframe. Finally, keep only Timestamp and value columns:

JavaScript

Note: For pd.to_datetime, I used an explicit format to avoid Pandas infer the datetime if there are any ambiguities with the day first.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement