python - 合并年和周列以在 python 中创建日期时间和排序

标签 python pandas datetime calendar

样本数据

Year  Week_No  Value
2015   52       3
2016   2        7
2015   51       5
2016   1        6
2015   50       4

下面是我试过的代码
import datetime
d = "2015-50"
r = datetime.datetime.strptime(d + '-1', "%Y-%W-%w")
print(r)
2015-12-14 00:00:00

如何继续创建日期时间列?

最佳答案

我认为在 Pandas 中最好使用 to_datetime 添加最后一个值 -1对于星期几:

df['datetime'] = pd.to_datetime(df.Year.astype(str) + '-' + 
                                df.Week_No.astype(str) + '-1', format="%Y-%W-%w")

print (df)
   Year  Week_No  Value   datetime
0  2015       52      3 2015-12-28
1  2016        2      7 2016-01-11
2  2015       51      5 2015-12-21
3  2016        1      6 2016-01-04
4  2015       50      4 2015-12-14

关于python - 合并年和周列以在 python 中创建日期时间和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59317102/

相关文章:

python - 在 Django 中更改模型会导致数据库损坏?

python - create() 需要 1 个位置参数但给出了 2 个?

python - 在Python中加载15GB文件

python - 每行的 Pandas 有条件替换

mysql - 按日期和时间选择记录

python - 使用 Beautiful Soup 提取嵌套在多个标签内的文本 — Python

python - Pandas - 从字典列表创建 df

pandas - 如何将非零填充的日期字符串转换为 pandas 中的有用日期

r - 对时间序列数据使用马尔可夫链

来自字符串的 PHP 日期时间