Pandas – 将浮点型列转换为日期时间

huangapple go评论97阅读模式
英文:

Pandas - Converting column of type float to date time

问题

我有一个包含两列float64对象的数据框。我尝试将它们转换为日期。

  1. col1, col2
  2. 43835.0, 0.145833
  3. 43835.0, 0.166667

期望输出:

  1. col1, col2
  2. 05/01/2020, 3:30:00 AM
  3. 05/01/2020, 4:00:00 AM

当我尝试使用pd.to_datetime(df['col1'])时,它将值转换为分别为1970-01-01 00:00:00.0000438351970-01-01的日期。

英文:

I have a Dataframe with 2 columns that are float64 objects. I am trying to convert these to dates.

  1. col1, col2
  2. 43835.0, 0.145833
  3. 43835.0, 0.166667

Expected output:

  1. col1, col2
  2. 05/01/2020,3:30:00 AM
  3. 05/01/2020, 4:00:00 AM

When I try pd.to_datetime(df['col1']) it convert the values to 1970-01-01 00:00:00.000043835 and 1970-01-01 respectively

答案1

得分: 2

首先,可以将第一列转换为日期时间,将第二列转换为时间差:

  1. df['col1'] = pd.to_timedelta(df['col1'], unit='d') + pd.to_datetime('1899-12-30')
  2. df['col2'] = pd.to_timedelta(df['col2'], unit='d').dt.floor('S')
  3. print(df)

输出结果:

  1. col1 col2
  2. 0 2020-01-05 03:29:59
  3. 1 2020-01-05 04:00:00

对于自定义日期和时间的想法,但由于精度输出略有不同:

  1. s = df['col1'] + df['col2']
  2. dates = pd.to_timedelta(s, unit='d').add(pd.to_datetime('1899-12-30')).dt.floor('S')
  3. df['col1'] = dates.dt.strftime('%d/%m/%Y')
  4. df['col2'] = dates.dt.strftime('%I:%M:%S %p')
  5. print(df)

输出结果:

  1. col1 col2
  2. 0 05/01/2020 03:29:59 AM
  3. 1 05/01/2020 04:00:00 AM
英文:

First is possible convert to datetimes fist column and second to timedeltas:

  1. df['col1'] = pd.to_timedelta(df['col1'], unit='d') + pd.datetime(1899, 12, 30)
  2. df['col2'] = pd.to_timedelta(df['col2'], unit='d').dt.floor('S')
  3. print (df)
  4. col1 col2
  5. 0 2020-01-05 03:29:59
  6. 1 2020-01-05 04:00:00

One idea for custom dates and times, but becuase precision output is a bit different:

  1. s = df['col1'] + df['col2']
  2. dates = pd.to_timedelta(s, unit='d').add(pd.datetime(1899, 12, 30)).dt.floor('S')
  3. df['col1'] = dates.dt.strftime('%d/%m/%Y')
  4. df['col2'] = dates.dt.strftime('%H:%M:%S %p')
  5. print (df)
  6. col1 col2
  7. 0 05/01/2020 03:29:59 AM
  8. 1 05/01/2020 04:00:00 AM

huangapple
  • 本文由 发表于 2020年1月6日 17:23:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定