首页 > 解决方案 > 将 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

标签: pythonpandasdataframedatetime

解决方案


因此,我们的主要任务是将YYYYWNor转换YYYYWNNYYYY-NN. 在哪里,YYYY是我们必须的,并且是。YearWStringreplaceNNNumber of Week

有两种情况可以更换。其解决方案的详细方案如下所述: -

1. 单数WN格式的一周(例如:- 2019W1):-

因此,要替换YYYYWNwithYYYY-NN我们必须使用replacewith 函数RegEx

RegEx对于identificationWNW(\d)$哪里:-

  • WCharacter 'W'我们必须更换的
  • (\d)用于识别Single Digit数字
  • $用于查找ending例如:-在我们的例子中是,(\d)$。所以,它会发现我们Pattern是否以个位数结尾。

RegEx对于ReplacementWN0\1哪里:-

  • 00:-在周数之前附加
  • \1Single Week Digit:-用于尾随0

2. 多位数WNN格式的一周(例如:- 2020W11):-

RegExfor identificationofWNN将在W哪里:-

  • WCharacter 'W'我们必须更换的

RegEx因为ReplacementWNN""

  • ""因为我们只需trim W要从Date

注意: -
我已经采取dummy datatesting目的。
为了达到期望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

推荐阅读