python - 将 yyyyWn 格式转换为 yyyyww - Python
问题描述
我有一个数据框,其中包含以下格式的数据:
ID Date Volume
1 2019W1 9
1 2020W2 11
2 2019W1 39
2 2020W2 23
我想将其转换为 yyyyww 格式。
df['Date'] = df['Date'].dt.strftime(%Y%U)
这段代码不太好用。
错误信息:
ValueError: ('Unknown string format: '2019W1')
预期输出:
ID Date Volume
1 2019-01 9
1 2020-02 11
2 2019-01 39
2 2020-02 23
解决方案
因此,我们的主要任务是将YYYYWN
or转换YYYYWNN
为YYYY-NN
. 在哪里,YYYY
是我们必须的,并且是。Year
W
String
replace
NN
Number of Week
有两种情况可以更换。其解决方案的详细方案如下所述: -
1. 单数WN
格式的一周(例如:- 2019W1):-
因此,要替换YYYYWN
withYYYY-NN
我们必须使用replace
with 函数RegEx
。
RegEx
对于identification
将WN
在W(\d)$
哪里:-
W
是Character 'W'
我们必须更换的(\d)
用于识别Single Digit
数字$
用于查找ending
。例如:-在我们的例子中是,(\d)$
。所以,它会发现我们Pattern
是否以个位数结尾。
RegEx
对于Replacement
将WN
在0\1
哪里:-
0
0
:-在周数之前附加\1
Single Week Digit
:-用于尾随0
2. 多位数WNN
格式的一周(例如:- 2020W11):-
RegEx
for identification
ofWNN
将在W
哪里:-
W
是Character 'W'
我们必须更换的
RegEx
因为Replacement
将WNN
是""
""
因为我们只需trim
W
要从Date
注意: -
我已经采取dummy data
了testing
目的。
为了达到期望Output
,必须正确运行这两个场景order
Code
对于相同的情况如下所述:-
# Import all-important Libraries
import pandas as pd
# Initialization of 'Data'
data = {
'ID': ['1', '1', '2', '2', '3', '3'],
'Date': ['2019W1', '2020W2', '2019W1', '2020W2', '2020W11', '2020W52'],
'Volume': ['9', '11', '39', '23', '34', '53']
}
# Conversion of 'Data' to 'DataFrame'
df = pd.DataFrame(data)
# Conversion of 'YYYYWN' to 'YYYYWW' Using 'Regex'
# Replacement Logic if your 'week No.' is of Single Digit. i.e.:- 'WN'
df['Date'] = df['Date'].replace(r"W(\d)$", "-" + r"0\1", regex = True)
# Replacement Logic if your 'week No.' is of Multiple Digit. i.e.:- 'WNN'
df['Date'] = df['Date'].replace(r"W", "-" + r"", regex = True)
# Print Records
df
# Output of Above Cell:-
ID Date Volume
0 1 2019-01 9
1 1 2020-02 11
2 2 2019-01 39
3 2 2020-02 23
4 3 2020-11 34
5 3 2020-52 53
推荐阅读
- google-sheets - Google Sheets =IF 公式偶尔在多张工作表中起作用
- regex - 字符相同时字符到字符的正则表达式
- arrays - Laravel required_without 数组中的验证规则
- sql - 根据另一个表oracle sql中的值动态更新多行
- javascript - 在 Qlik 中选择任何 KPI 框的动态图表
- python - 尝试为 plotly 中的每个条形子图制作统一的色阶(python)
- java - 如何通过改造从安卓设备上传照片?
- excel - VBA 过滤和复制 - 更短的例程?
- angular - Angular:为什么'keydown'事件监听器会多次触发?
- c# - 如何检查切换是否已切换,然后激活对象作为响应?