简体   繁体   English

在熊猫中将“年”和“年中的星期”列转换为“日期”

[英]Converting “year” and “week of year” columns to “date” in Pandas

Desired way 所需方式

In order to convert two columns with year and week of year into date I would expect to do something like: 为了将年份和年份的两列转换为日期,我希望执行以下操作:

df['formatted_date'] = df.year*100+df.weekofyear
df['date'] = pd.to_datetime(df['formatted_date'], format='%Y%w')

However, it does not work, giving ValueError : 但是,它不起作用,给出ValueError

ValueError: unconverted data remains: 01

Workaround 解决方法

The workaround, I have found is converting week of year into a day of year and working with year-dayofyear %Y%j format: 我发现解决方法是将一年中的星期转换为一年中的某一天,并使用year-dayofyear %Y%j格式:

df['formatted_date'] = df.year*1000+df.weekofyear*7-6 
df['date'] = pd.to_datetime(df['formatted_date'], format='%Y%j')

The first line becomes ugly, but this works fine. 第一行很丑陋,但是效果很好。 Week of year is in the range (00,53). 一年中的星期在(00,53)范围内。 Any ideas, why is the elegant way not working? 有什么想法,为什么优雅的方式不起作用?

You need combine %w for day of week - explanation with %W for week: 您需要将%w组合成一周的某天-用%W进行解释

http://strftime.org/ for %W : http://strftime.org/用于%W

Week number of the year (Monday as the first day of the week) as a decimal number. 一年中的星期数(星期一为一周的第一天),以十进制数表示。 All days in a new year preceding the first Monday are considered to be in week 0. 第一个星期一之前的新的一年中的所有天均视为在第0周。

And for %w : 对于%w

Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 以十进制数表示的工作日,其中0是星期日,6是星期六。


df = pd.DataFrame({'year':[2015, 2018],
                   'weekofyear':[10,12]})

dates = df.year*100+df.weekofyear
@adde
df['date'] = pd.to_datetime(dates.astype(str) + '0', format='%Y%W%w')
print (df)

   year  weekofyear  formatted_date       date
0  2015  10          201510         2015-03-15
1  2018  12          201812         2018-03-25

Another solution: 另一个解决方案:

#added 0 only for demontration, you can remove it
df['formatted_date'] = df.year * 1000 + df.weekofyear * 10 + 0
df['date'] = pd.to_datetime(df['formatted_date'], format='%Y%W%w')
print (df)

   year  weekofyear  formatted_date       date
0  2015  10          2015100        2015-03-15
1  2018  12          2018120        2018-03-25

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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