使用Python和Pandas将周数转换为日期

huangapple go评论71阅读模式
英文:

Convert Weeknumber to date using Python and Pandas

问题

我需要帮助从我的数据框中提取周日期:

df = pd.DataFrame({
    'weeknum':[12,24,36,48,50],
    'year':[2023,2023,2023,2023,2023]
})

我期望的输出是有一个新列名为"weekDate",该列将以"yyyy-MM-dd"格式提取特定周的第一个星期一的日期:

例如,对于周:12,年:2023 ====> "2023-03-20"(这是2023年第12周的第一个星期一的日期)

非常感谢提前帮助。

英文:

I need help extracting the weekdate from my df:

df = pd.DataFrame({
    'weeknum':[12,24,36,48,50],
    'year':[2023,2023,2023,2023,2023]
})

my desired output is to have a new column named "weekDate" which will pull the date of the first Monday of the specific week in a "yyyy-MM-dd" format:

E.g. for Week: 12, Year: 2023 ====> "2023-03-20" (which is the first Monday of week 12 in 2023)

Many thanks in advance,

答案1

得分: 1

To convert week numbers to dates, you can use the datetime module with the pandas library.

import pandas as pd
from datetime import datetime, timedelta

df = pd.DataFrame({
    'weeknum':[12,24,36,48,50],
    'year':[2023,2023,2023,2023,2023]
})

# Function to get the date of the first Monday of a given week and year
def get_first_monday(year, week):
    date_str = f'{year}-W{week}'
    date_obj = datetime.strptime(date_str + '-1', "%Y-W%W-%w")
    return date_obj.strftime('%Y-%m-%d')

# Apply the function to create the 'weekDate' column
df['weekDate'] = df.apply(lambda row: get_first_monday(row['year'], row['weeknum']), axis=1)

print(df)

Output

   weeknum  year    weekDate
0       12  2023  2023-03-20
1       24  2023  2023-06-12
2       36  2023  2023-09-04
3       48  2023  2023-11-27
4       50  2023  2023-12-11
英文:

To convert week numbers to dates, you can use the datetime module with the pandas library.

import pandas as pd
from datetime import datetime, timedelta


df = pd.DataFrame({
    'weeknum':[12,24,36,48,50],
    'year':[2023,2023,2023,2023,2023]
})

# Function to get the date of the first Monday of a given week and year
def get_first_monday(year, week):
    date_str = f'{year}-W{week}'
    date_obj = datetime.strptime(date_str + '-1', "%Y-W%W-%w")
    return date_obj.strftime('%Y-%m-%d')

# Apply the function to create the 'weekDate' column
df['weekDate'] = df.apply(lambda row: get_first_monday(row['year'], row['weeknum']), axis=1)

print(df)

Output

   weeknum  year    weekDate
0       12  2023  2023-03-20
1       24  2023  2023-06-12
2       36  2023  2023-09-04
3       48  2023  2023-11-27
4       50  2023  2023-12-11

答案2

得分: 0

你可以连接这些列并使用to_datetime'%Y-%W-%w'格式(更多信息请看这里):

df['weekDate'] = pd.to_datetime(
               df['year'].astype(str)+'-'+df['weeknum'].astype(str)+'-1',
               format='%Y-%W-%w')            #                        ^
                                             #          1 is for Monday
# or                                         #                   |
df['weekDate'] = pd.to_datetime(             #                   v
               df['year'].astype(str)+df['weeknum'].astype(str)+'1',
               format='%Y%W%w')

输出:

   weeknum  year   weekDate
0       12  2023 2023-03-20
1       24  2023 2023-06-12
2       36  2023 2023-09-04
3       48  2023 2023-11-27
4       50  2023 2023-12-11
英文:

You can concatenate the columns and use to_datetime with the '%Y-%W-%w' format (more info here):

df['weekDate'] = pd.to_datetime(
               df['year'].astype(str)+'-'+df['weeknum'].astype(str)+'-1',
               format='%Y-%W-%w')            #                        ^
                                             #          1 is for Monday
# or                                         #                   |
df['weekDate'] = pd.to_datetime(             #                   v
               df['year'].astype(str)+df['weeknum'].astype(str)+'1',
               format='%Y%W%w')

Output:

   weeknum  year   weekDate
0       12  2023 2023-03-20
1       24  2023 2023-06-12
2       36  2023 2023-09-04
3       48  2023 2023-11-27
4       50  2023 2023-12-11

huangapple
  • 本文由 发表于 2023年6月21日 22:54:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76524628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定