简体   繁体   中英

Pandas convert two separate columns into a single datetime column?

I have two columns in a pandas dataframe that I want to convert into a single datetime column. The problem is that one of the columns is the week of the year and one is the actual year. It looks something like this:

WEEK_OF_YEAR | YEAR
1              2016
2              2016  
...
52             2016
1              2017
2              2017
3              2017
...
52             2017
1              2018

How can I make another column called "DATE" that is the datetime conversion of both columns together?

If converting week of year is necesary define day of week by %w :

%w - Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

#for Sundays is set value to 0
s = df['WEEK_OF_YEAR'].astype(str)  + '-0-' + df['YEAR'].astype(str)
df['date'] = pd.to_datetime(s, format='%W-%w-%Y')
print (df)
   WEEK_OF_YEAR  YEAR       date
0             1  2016 2016-01-10
1             2  2016 2016-01-17
2            52  2016 2017-01-01
3             1  2017 2017-01-08
4             2  2017 2017-01-15
5             3  2017 2017-01-22
6            52  2017 2017-12-31
7             1  2018 2018-01-07

Try this:

import time

df.DATE = time.asctime(time.strptime('{} {} 1'.format(df.YEAR, df.WEEK_OF_YEAR), '%Y %W %w'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM