【问题标题】:Convert a column of dates from ordinal numbers to the standard date format - pandas将一列日期从序数转换为标准日期格式 - pandas
【发布时间】:2019-03-18 14:57:48
【问题描述】:

我必须将一列日期从整数/日期格式转换为日期格式 d-m-Y。示例:

import pandas as pd
col1 = [737346, 737346, 737346, 737346, 737059, 737346]
col2 = ['cod1', 'cod2', 'cod3', 'cod4', 'cod1', 'cod2']
dict = {'V1' : col1, 'V2' : col2}   
df = pd.DataFrame.from_dict(dict)

df

       V1    V2
0  737346  cod1
1  737346  cod2
2  737346  cod3
3  737346  cod4
4  737059  cod1
5  737346  cod2

预期:

df
           V1    V2
0  14-10-2019  cod1
1  14-10-2019  cod2
2  14-10-2019  cod3
3  14-10-2019  cod4
4  31-12-2018  cod1
5  14-10-2019  cod2

【问题讨论】:

    标签: python pandas date integer calculated-columns


    【解决方案1】:

    datetime fromordinal 应该会有所帮助。

    import datetime as dt
    
    col1 = [737346, 737346, 737346, 737346, 737059, 737346]
    col2 = ['cod1', 'cod2', 'cod3', 'cod4', 'cod1', 'cod2']
    dd = {'V1' : col1, 'V2' : col2}   
    df = pd.DataFrame.from_dict(dd)
    
    df['V1'] = df['V1'].apply(dt.datetime.fromordinal)
    

    【讨论】:

    • 更好的是df['V1'] = df['V1'].apply(dt.datetime.fromordinal).dt.strftime('%d-%m-%Y') 以获得所需的日期时间格式
    • @yatu date.fromordinalint 作为输入
    【解决方案2】:

    pandasTimestamp.fromordinal

    df.V1.map(pd.Timestamp.fromordinal)
    Out[511]: 
    0   2019-10-14
    1   2019-10-14
    2   2019-10-14
    3   2019-10-14
    4   2018-12-31
    5   2019-10-14
    Name: V1, dtype: datetime64[ns]
    

    【讨论】:

      【解决方案3】:

      您可以为此使用date.fromordinal

      from datetime import datetime as dt
      
      df['V1'] = df.V1.apply(lambda x: dt.fromordinal(x)).dt.strftime('%d-%m-%Y')
      
      print(df)
                 V1    V2
      0  14-10-2019  cod1
      1  14-10-2019  cod2
      2  14-10-2019  cod3
      3  14-10-2019  cod4
      4  31-12-2018  cod1
      5  14-10-2019  cod2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2013-01-08
        相关资源
        最近更新 更多