将年、月、周数和日组合到d

2024-09-25 16:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

year  month  week_num    day
2019   8       31       Thurs
2019   8       31        Fri
2019   8       32        Tues

日的缩写是MonTuesWedsThursFriSatSun。你知道吗

我想生成另一列,它将提供yyyy-mm-dd格式的日期。我该怎么做?提前谢谢!你知道吗


Tags: 数据yearsatnumsunmmweekday
1条回答
网友
1楼 · 发布于 2024-09-25 16:27:41

模块^{}给你这个机会。This discussion说明如何从周数中获取日期。你知道吗

然后,您可以定义一个函数来获取日期并将其应用于数据帧。你知道吗

代码如下:

# Import modules
import datetime

# Your data
df = pd.DataFrame([
                   [2019, 8, 29, "Fri"],
                    [2019, 8, 31, "Sun"],
                   [2019, 8, 29, "Tues"]],
                  columns=["year", "month", "week_num", "day"])

# A value per day
val_day = {"Mon": 0, "Tues": 1, "Weds": 2, "Thurs": 3,
           "Fri": 4, "Sat": 5, "Sun": 6}

# Get the date from the year, number of week and the day


def getDate(row):
    # Create string format
    str_date = "{0}-W{1}-1".format(row.year,
                                     row.week_num - 1)
    print(str_date)
    # Get the date
    date = datetime.datetime.strptime(
        str_date, "%Y-W%W-%w") + datetime.timedelta(days=val_day[row.day])
    # Update date field
    row["date"] = date.strftime("%Y-%m-%d")
    return row


# apply the function to each row
df = df.apply(getDate, axis=1)
print(df)
#    year  month  week_num    day        date
# 0  2019      8         1  Thurs  2019-01-03
# 1  2019      8        29    Fri  2019-07-19
# 2  2019      8        29   Tues  2019-07-16

相关问题 更多 >