代码之家  ›  专栏  ›  技术社区  ›  FaCoffee

如何将年、月和日列组合到单个datetime列?

  •  5
  • FaCoffee  · 技术社区  · 7 年前

    我有以下数据框 df :

            id  lat        lon      year    month   day         
    0       381 53.30660   -0.54649 2004    1       2       
    1       381 53.30660   -0.54649 2004    1       3            
    2       381 53.30660   -0.54649 2004    1       4   
    

    我想创建一个新列 df['Date'] 其中 year , month day 根据格式组合列 yyyy-m-d .

    下列的 this post ,我做到了:

    `df['Date']=pd.to_datetime(df['year']*10000000000
                               +df['month']*100000000
                               +df['day']*1000000,
                               format='%Y-%m-%d%')`
    

    结果不是我所期望的,因为它从1970年开始,而不是从2004年开始,而且它还包含小时戳,我没有具体说明:

            id  lat        lon      year    month   day  Date           
    0       381 53.30660   -0.54649 2004    1       2    1970-01-01 05:34:00.102    
    1       381 53.30660   -0.54649 2004    1       3    1970-01-01 05:34:00.103         
    2       381 53.30660   -0.54649 2004    1       4    1970-01-01 05:34:00.104
    

    因为日期应该在 2004-1-2 format,我做错了什么?

    4 回复  |  直到 6 年前
        1
  •  14
  •   MaxU - stand with Ukraine    7 年前

    有一种更简单的方法:

    In [250]: df['Date']=pd.to_datetime(df[['year','month','day']])
    
    In [251]: df
    Out[251]:
        id      lat      lon  year  month  day       Date
    0  381  53.3066 -0.54649  2004      1    2 2004-01-02
    1  381  53.3066 -0.54649  2004      1    3 2004-01-03
    2  381  53.3066 -0.54649  2004      1    4 2004-01-04
    

    从…起 docs :

    从数据帧的多个列组装datetime。钥匙 可以是常见的缩写,如[ year , month , day , minute , second , ms , us , ns ])或相同的复数

        2
  •  7
  •   cs95 abhishek58g    6 年前

    一种解决方案是将这些列转换为字符串,并使用 agg + str.join ,然后转换为 datetime .

    df['Date'] = pd.to_datetime(
        df[['year', 'month', 'day']].astype(str).agg('-'.join, axis=1))
    
    df
    
        id      lat      lon  year  month  day       Date
    0  381  53.3066 -0.54649  2004      1    2 2004-01-02
    1  381  53.3066 -0.54649  2004      1    3 2004-01-03
    2  381  53.3066 -0.54649  2004      1    4 2004-01-04
    

    您可能还需要添加 errors='coerce' 参数,如果列之间的日期时间组合无效。

        3
  •  4
  •   BENY    7 年前

    修复您的代码

    df['Date']=pd.to_datetime(df.year*10000+df.month*100+df.day,format='%Y%m%d')
    df
    Out[57]: 
        id      lat      lon  year  month  day       Date
    0  381  53.3066 -0.54649  2004      1    2 2004-01-02
    1  381  53.3066 -0.54649  2004      1    3 2004-01-03
    2  381  53.3066 -0.54649  2004      1    4 2004-01-04
    
        4
  •  1
  •   user3344221    5 年前

    我很难找到解决方案,因为我正在处理一个包含西班牙语列的数据集。当我把它们翻译成“年”、“月”、“日”和“小时”时,转换工作就完成了