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

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

Pandas - Converting column of type float to date time

问题

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

col1, col2
43835.0, 0.145833
43835.0, 0.166667

期望输出:

col1, col2
05/01/2020, 3:30:00 AM
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.

col1, col2
43835.0, 0.145833
43835.0, 0.166667

Expected output:

col1, col2
05/01/2020,3:30:00 AM
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

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

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

输出结果:

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

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

s = df['col1'] + df['col2']
dates = pd.to_timedelta(s, unit='d').add(pd.to_datetime('1899-12-30')).dt.floor('S')

df['col1'] = dates.dt.strftime('%d/%m/%Y')
df['col2'] = dates.dt.strftime('%I:%M:%S %p')
print(df)

输出结果:

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

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

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

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

s = df['col1'] + df['col2']
dates = pd.to_timedelta(s, unit='d').add(pd.datetime(1899, 12, 30)).dt.floor('S')

df['col1'] = dates.dt.strftime('%d/%m/%Y')
df['col2'] = dates.dt.strftime('%H:%M:%S %p')
print (df)
         col1         col2
0  05/01/2020  03:29:59 AM
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:

确定