gpt4 book ai didi

python - 在 Pandas 中将 "year"和 "week of year"列转换为 "date"

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:34 25 4
gpt4 key购买 nike

期望的方式

为了将包含年份和年份中的星期的两列转换为日期,我希望这样做:

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

但是,它不起作用,给出 ValueError:

ValueError: unconverted data remains: 01

解决方法

我发现的解决方法是将一年中的星期转换为一年中的一天,并使用年-日 %Y%j 格式:

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

第一行变得丑陋,但这工作正常。一年中的第几周在 (00,53) 范围内。任何想法,为什么优雅的方式不起作用?

最佳答案

您需要为星期几组合 %w - explanation %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.

对于%w:

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


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

另一种解决方案:

#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

关于python - 在 Pandas 中将 "year"和 "week of year"列转换为 "date",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55222420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com