【问题标题】:What's the best way to combine multiple columns as single datetime将多列组合为单个日期时间的最佳方法是什么
【发布时间】:2021-06-06 22:21:42
【问题描述】:

这是我不时回来的一个问题。我有一个数据集,其中使用多个列(还有其他列,这些只是与问题相关的列)用于指示日期和时间。在将它们从 float 转换为 int 之后,我现在有了:

year    mo      dy  hr min sec Valid Mag
1234    1886    9   1   2   51  4.0 7.3
1286    1893    6   4   2   27  4.0 7.0
1329    1897    8   5   0   10  4.0 7.7
1366    1901    8   9   9   23  4.0 7.2
1368    1901    8   9   18  33  4.0 7.4

在 DataFrame 中将其转换为 DateTime 的最清晰和最惯用的方法是什么?不仅仅是与日期和时间相关的列?

我在另一个项目中使用了这个:

sun['Date'] = sun['Year'].map(str)+ '-' + sun['Month'].map(str) + '-' + sun['Day'].map(str)
pd.to_datetime(sun['Date'], utc=False)

虽然这可行,但我认为肯定有更好、更通用的方法。具体来说,我希望将相关字段组合到 DateTime 中,但是,数据框中还有其他字段。我在 SQL 中看到了对此的良好响应,但这不是我想要的。

编辑:我收到了一些关于日期和时间的 DataFrames 的可靠答案。但是,问题是所有都会导致相同的错误“ValueError:长度不匹配:预期轴有 19 个元素,新值有 6 个元素”所以我添加了几个额外的列。

【问题讨论】:

    标签: python pandas datetime python-datetime


    【解决方案1】:

    更改列名然后pd.to_datetime

    df.columns = ['year','month','day','hour','minute','second']
    out = pd.to_datetime(df)
    Out[185]: 
    1234   1886-09-01 02:51:00
    1286   1893-06-04 02:27:00
    1329   1897-08-05 00:10:00
    1366   1901-08-09 09:23:30
    1368   1901-08-09 18:33:45
    dtype: datetime64[ns]
    

    【讨论】:

    • 如果只有这六列,那效果很好,但因为还有多个其他列。你得到一个类型不匹配。
    • @hrokr 尝试使用rename 然后 df = df.rename({'Year' : 'year'....}), df['New'] = pd.to_datetime(df[ ['年','月','日','小时','分钟','秒']])
    【解决方案2】:

    强制 df 为字符串

    使用str.pad 将值填充到最小值 2

    使用str.cat 组合值

    将结果强制转换为日期时间对象。

    代码如下

    pd.to_datetime(df.astype(str).apply(lambda x: (x.str.pad(width=2, side='left', fillchar='0')).str.cat(sep=''),axis=1))
    
    1234   1886-09-01 02:51:00
    1286   1893-06-04 02:27:00
    1329   1897-08-05 00:10:00
    1366   1901-08-09 09:23:30
    1368   1901-08-09 18:33:45
    

    【讨论】:

      【解决方案3】:

      所以这是一种方法,我不知道它是否惯用。

      我找到的解决方案是使用这些列名

      df.columns = [ 'year', 'month' , 'day' , 'hour' , 'minute'  ,'seconds']
      
      df = pd.DataFrame([[1886,9,1,2,51,0],
      [1893,6,4,2,27,0],
      [1897,8,5,0,10,0],
      [1901,8,9,9,23,30],
      [1901,8,9,18,33,45]])
      
      #df.columns = [ 'Year', 'Mo' , 'Dy' , 'Hr' , 'Mn'  ,'Sec']
      
      #use these column names instead of what you have
      df.columns = [ 'year', 'month' , 'day' , 'hour' , 'minute'  ,'seconds']
      
      #then you convert to date time
      pd.to_datetime(df)
      
      #output
      0   1886-09-01 02:51:00
      1   1893-06-04 02:27:00
      2   1897-08-05 00:10:00
      3   1901-08-09 09:23:30
      4   1901-08-09 18:33:45
      dtype: datetime64[ns]
      

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

      【讨论】:

      • 这有效,但仅适用于日期时间列表。我正在为带有数据的完整 DataFrame 寻找一个优雅的解决方案。
      【解决方案4】:

      实现此目的的另一种方法是使用datetime.strptime() 创建一个datetime 对象并将df.apply() 它添加到一个新列中。

      df['time'] = df.apply(lambda r: datetime.strptime(f"{r['Year']} {r['Mo']} {r['Dy']} {r['Hr']}:{r['Mn']}:{r['Sec']}", '%Y %m %d %H:%M:%S'), axis=1)
      

      输出:

      df['time']
      1234   1886-09-01 02:51:00
      1286   1893-06-04 02:27:00
      1329   1897-08-05 00:10:00
      1366   1901-08-09 09:23:30
      1368   1901-08-09 18:33:45
      Name: time, dtype: datetime64[ns]
      

      【讨论】:

      • 这适用于带有数据的数据框,我已经赞成。我将推迟接受,看看是否会出现更优雅的解决方案。但我认为对于那些后来遇到同样问题的人来说,将其视为可行是很重要的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      相关资源
      最近更新 更多