2017-03-01 86 views
1

我想通過設定一個恆定的年,月,日,分,秒,只保留了大熊貓:保留小時,同時設定日期不變,分

import pandas as pd 
td = pd.DataFrame(['2015-01-01 09:03:00', '2015-01-11 15:47:00', 
      '2015-01-11 16:47:00', '2015-01-11 01:47:00', '2016-01-11 01:47:00'], columns=['datetime']) 
td['datetime'] = pd.to_datetime(td['datetime']) 


    datetime 
0 2015-01-01 09:03:00 
1 2015-01-11 15:47:00 
2 2015-01-11 16:47:00 
3 2015-01-11 01:47:00 
4 2016-01-11 01:47:00 
創建日期時間的新列

結果應該看起來像這樣。

datetime 
0 1900-01-01 09:00:00 
1 1900-01-01 15:00:00 
2 1900-01-01 16:00:00 
3 1900-01-01 01:00:00 
4 1900-01-01 01:00:00 

我該如何編碼?謝謝!

回答

2

使用pd.to_timedelta

pd.to_datetime('1900-01-01') + pd.to_timedelta(td.datetime.dt.hour, unit='H') 

0 1900-01-01 09:00:00 
1 1900-01-01 15:00:00 
2 1900-01-01 16:00:00 
3 1900-01-01 01:00:00 
4 1900-01-01 01:00:00 
Name: datetime, dtype: datetime64[ns] 
1
td['datetime'].apply(lambda x: datetime(1900, 1, 1) + timedelta(hours=x.hour)) 

0 1900-01-01 09:00:00 
1 1900-01-01 15:00:00 
2 1900-01-01 16:00:00 
3 1900-01-01 01:00:00 
4 1900-01-01 01:00:00 
Name: datetime, dtype: datetime64[ns] 
相關問題