【问题标题】:How to combine year, month, and day columns to single datetime column?如何将年、月和日列合并到单个日期时间列?
【发布时间】:2018-06-17 18:08:42
【问题描述】:

我有以下数据框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'],其中yearmonthday 列根据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 格式,我做错了什么?

【问题讨论】:

    标签: python pandas date datetime timestamp


    【解决方案1】:

    有一个更简单的方法:

    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

    从 DataFrame 的多列中组装日期时间。按键 可以是常见的缩写,如 [year, month, day, minute, second, ms, us, ns]) 或相同的复数形式

    【讨论】:

    • 这对我来说是新的,真的很漂亮。
    • @cᴏʟᴅsᴘᴇᴇᴅ,这让我很惊讶 - 这是一个古老的功能;)
    【解决方案2】:

    一种解决方案是将这些列转换为字符串,使用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】:

      修复你的代码

      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】:

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

        【讨论】:

          猜你喜欢
          • 2022-07-22
          • 2022-06-28
          • 2021-11-17
          • 2019-07-11
          • 2013-11-29
          • 1970-01-01
          • 2015-12-23
          • 1970-01-01
          • 2019-02-20
          相关资源
          最近更新 更多