gpt4 book ai didi

python - 基于日历函数创建新列

转载 作者:行者123 更新时间:2023-12-01 08:47:24 25 4
gpt4 key购买 nike

我有一个数据框:

    Year     Month    Week_of_month Day_of_week 
0 2018 1 2 1
1 2018 1 1 2
2 2018 1 2 2
3 2018 1 1 3
4 2018 1 2 3
5 2018 1 1 4
6 2018 1 2 4
7 2018 1 1 5
8 2018 1 2 5
9 2018 1 1 6
10 2018 1 2 6
11 2018 1 1 7

其中包含:

  • Day of week (1 to 7 -> Sunday until Saturday)

  • Week of the month (1 until 6 - One month has a maximum of 6 weeks)

我想根据这4个信息得到对应的日期:

例如,为了获取 2018 年 12 月 30 日,我这样做了:

Image

我使用了这个函数:

calendar.setfirstweekday(calendar.SUNDAY)
calendar.monthcalendar(2018,12)

[[0, 0, 0, 0, 0, 0, 1],
[2, 3, 4, 5, 6, 7, 8],
[9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22],
[23, 24, 25, 26, 27, 28, 29],
[30, 31, 0, 0, 0, 0, 0]]

calendar.monthcalendar(2018,12)[5][1]
31

重点是:如何使用此函数获取数据框每一行中的每一天?.

我尝试过这个:

df['Day'] = calendar.monthcalendar(df.Year, df.Month)[df.Week_of_month][df.Day_of_week]

但是,我遇到了错误:

TypeError: '>=' not supported between instances of 'str' and 'int'

最佳答案

给你:

df['Day'] = df.apply(lambda x: calendar.monthcalendar(x.Year, x.Month)[x.Week_of_month-1][x.Day_of_week-1], axis=1)

输出:

enter image description here

希望这有帮助。

关于python - 基于日历函数创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245946/

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