0

i have a dataframe called "dates" with shape 4380,1 that looks like this -

                   date
0    2017-01-01 00:00:00
1    2017-01-01 06:00:00
2    2017-01-01 12:00:00
3    2017-01-01 18:00:00
4    2017-01-02 00:00:00
             ...
4375 2019-12-30 18:00:00
4376 2019-12-31 00:00:00
4377 2019-12-31 06:00:00
4378 2019-12-31 12:00:00
4379 2019-12-31 18:00:00 

but i need to divide the single column of dates by the delimiter "-" or dash so that I can use this to groupby the month e.g., 01, 02,...12. So, my final result for the new dataframe should have shape 4380,4 and look like:

     Year Month Day HHMMSS
0    2017 01 01 00:00:00
1    2017 01 01 06:00:00
       ...
4379 2019 12 31 18:00:00

I cannot find how to do this python transformation from single to multiple columns based on a delimiter. Thank you much!

ansev
  • 30,322
  • 5
  • 17
  • 31
user2100039
  • 1,280
  • 2
  • 16
  • 31
  • _I cannot find how to do this python transformation from single to multiple columns based on a delimiter._ How is that possible? A simple search for "pandas split string based on delimiter" returns https://stackoverflow.com/questions/37333299/splitting-a-column-by-delimiter-pandas-python. Also, why not use proper date/time operations? – AMC Mar 12 '20 at 18:26
  • Does this answer your question? [Extracting just Month and Year separately from Pandas Datetime column](https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-separately-from-pandas-datetime-column) – AMC Mar 12 '20 at 18:28
  • this is not dupe – ansev Mar 12 '20 at 18:39

1 Answers1

0

Use Series.dt.strftime and Series.str.split:

new_df = df['date'].dt.strftime('%Y-%m-%d-%H:%M:%S').str.split('-',expand=True)
new_df.columns = ['Year','Month','Day', 'HHMMSS']
print(new_df)
      Year Month Day    HHMMSS
0     2017    01  01  00:00:00
1     2017    01  01  06:00:00
2     2017    01  01  12:00:00
3     2017    01  01  18:00:00
4     2017    01  02  00:00:00
4375  2019    12  30  18:00:00
4376  2019    12  31  00:00:00
4377  2019    12  31  06:00:00
4378  2019    12  31  12:00:00
4379  2019    12  31  18:00:00
ansev
  • 30,322
  • 5
  • 17
  • 31