【问题标题】:How to normalize the following dates inside a pandas dataframe?如何规范化熊猫数据框中的以下日期?
【发布时间】:2017-07-10 08:20:26
【问题描述】:

我有以下dates 数据框:

   dates
0  2012 10 4
1
2  2012 01 19
3  20 6 11
4  20 10 7
5  19 11 12
6
7  2013 03 19
8  2016 2 5
9  2011 2 19
10
11  2011 05 23
12  2012 04 5

如何将日期列标准化为:

     dates
0  2012 10 04
1
2  2012 01 19
3  2020 06 11
4  2020 10 07
5  2019 11 12
6
7  2013 03 19
8  2016 02 05
9 2011 02 19
10
11 2011 05 23
12 2012 04 05

我尝试使用正则表达式并分别拆分和调整每一列。但是,我使任务复杂化。是否可以将其规范化为后一个数据帧?规则是如果年份不完整,则在字符串开头添加0,如果年份不完整,则在字符串开头添加20,格式为yyyymmdd

【问题讨论】:

    标签: python regex python-3.x pandas datetime


    【解决方案1】:

    解决方案:

    x = (df.loc[df.dates.str.contains(r'\d+\s*\d+\s*\d+'), 'dates']
           .str.split(expand=True)
           .rename(columns={0:'year',1:'month',2:'day'})
           .astype(int)
    )
    x.loc[x.year <= 50, 'year'] += 2000
    df['new'] = pd.to_datetime(x, errors='coerce').dt.strftime('%Y%m%d')
    

    结果:

    In [148]: df
    Out[148]:
             dates       new
    0    2012 10 4  20121004
    1                    NaN
    2   2012 01 19  20120119
    3      20 6 11  20200611
    4      20 10 7  20201007
    5     19 11 12  20191112
    6                    NaN
    7   2013 03 19  20130319
    8     2016 2 5  20160205
    9    2011 2 19  20110219
    10                   NaN
    11  2011 05 23  20110523
    12   2012 04 5  20120405
    

    解释:

    In [149]: df.loc[df.dates.str.contains(r'\d+\s*\d+\s*\d+'), 'dates']
    Out[149]:
    0      2012 10 4
    2     2012 01 19
    3        20 6 11
    4        20 10 7
    5       19 11 12
    7     2013 03 19
    8       2016 2 5
    9      2011 2 19
    11    2011 05 23
    12     2012 04 5
    Name: dates, dtype: object
    
    In [152]: (df.loc[df.dates.str.contains(r'\d+\s*\d+\s*\d+'), 'dates']
         ...:    .str.split(expand=True)
         ...:    .rename(columns={0:'year',1:'month',2:'day'})
         ...:    .astype(int))
    Out[152]:
        year  month  day
    0   2012     10    4
    2   2012      1   19
    3     20      6   11
    4     20     10    7
    5     19     11   12
    7   2013      3   19
    8   2016      2    5
    9   2011      2   19
    11  2011      5   23
    12  2012      4    5
    

    【讨论】:

    • 呵呵,再次提供一个REPRODUCIBLE数据集;)
    • 嗯,在您的“较短”版本中,没有像 '09T' 这样的“数字”
    • 提示:首先清理您的数据:df.dates = df.dates.str.replace(r'\D+', ' ') 然后使用我的答案中的解决方案...
    • 似乎有些值有字母....应用最后一个正则表达式后,这个问题就解决了。
    • @tumbleweed,不客气。下次请提供可重复的数据集 - 这将大大节省您和我们的时间
    猜你喜欢
    • 2017-05-04
    • 2020-10-21
    • 2014-12-12
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    相关资源
    最近更新 更多