简体   繁体   English

将年,月和日转换为日期时间

[英]Converting year, month and day to datetime

I have the foll. 我有傻瓜。 datafrme: datafrme:

     YEAR   MO   DY  name_col 
0  2016.0  1.0  5.0     0.00 
1  2016.0  1.0  6.0     0.00 
2  2016.0  1.0  7.0     0.41 
3  2016.0  1.0  8.0     0.53 
4  2016.0  1.0  9.0     2.12 

How do I convert the YEAR, MO and DY columns representing year, month and day respectively to datetime? 如何将分别代表年,月和日的YEAR,MO和DY列转换为日期时间?

     YEAR   MO   DY  name_col   datetime
0  2016.0  1.0  5.0     0.00 2016-01-05
1  2016.0  1.0  6.0     0.00 2016-01-06
2  2016.0  1.0  7.0     0.41 2016-01-07
3  2016.0  1.0  8.0     0.53 2016-01-08
4  2016.0  1.0  9.0     2.12 2016-01-09

I tried this: 我尝试了这个:

pd.to_datetime(df_met['YEAR'].astype(int), format='%Y') + pd.to_timedelta(df_met['DY'] - 1, unit='d')

pd.to_datetime() can assemble datetime from multiple columns if columns have "correct" names: 如果列具有“正确的”名称,则pd.to_datetime()可以从多个列中组合日期时间:

In [106]: df
Out[106]:
     YEAR   MO   DY  name_col
0  2016.0  1.0  5.0      0.00
1  2016.0  1.0  6.0      0.00
2  2016.0  1.0  7.0      0.41
3  2016.0  1.0  8.0      0.53
4  2016.0  1.0  9.0      2.12

In [107]: df['datetime'] = pd.to_datetime(df.rename(columns={'MO':'MONTH', 'DY':'DAY'}).drop('name_col', 1))

In [108]: df
Out[108]:
     YEAR   MO   DY  name_col   datetime
0  2016.0  1.0  5.0      0.00 2016-01-05
1  2016.0  1.0  6.0      0.00 2016-01-06
2  2016.0  1.0  7.0      0.41 2016-01-07
3  2016.0  1.0  8.0      0.53 2016-01-08
4  2016.0  1.0  9.0      2.12 2016-01-09

from docs : 来自docs

Assembling a datetime from multiple columns of a DataFrame. 从DataFrame的多个列中组合一个日期时间。 The keys can be common abbreviations like 键可以是常见的缩写,例如

['year', 'month', 'day', 'minute', 'second', 'ms', 'us', 'ns']

or plurals of the same 或相同的复数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM