2014-07-15 60 views
3

我正在處理一個數據集,它將日期編碼爲自1899年12月以來的整數月份,所以第一個月是1900年1月,第1165月是1997年1月。我想轉換爲pandas DateTimeIndex。到目前爲止,我想出最好的是:在Python /熊貓中,我如何將世紀月轉換爲DateTimeIndex?

month0 = np.datetime64('1899-12-15') 
one_month = np.timedelta64(30, 'D') + np.timedelta64(10.5, 'h') 
birthdates = pandas.DatetimeIndex(month0 + one_month * resp.cmbirth) 

開始日期是本月15日,和timedelta爲30天10.5小時,一個歷月的平均長度。所以本月內的日期會漂移一兩天。

所以這看起來有點不好意思,我想知道是否有更好的方法。

回答

3

您可以使用內置的pandas日期時間功能。

import pandas as pd 
import numpy as np 

indexed_months = np.random.random_integers(0, high=1165, size=100) 
month0 = pd.to_datetime('1899-12-01') 
date_list = [month0 + pd.DateOffset(months=mnt) for mnt in indexed_months] 
birthdates = pd.DatetimeIndex(date_list) 

我做了你的resp.cmbirth物體看起來像整數0和1165

我不太清楚之間的陣列上爲什麼你想要索引的bin邊緣是一個假設從月初或月末抵消。這可以做到:

shifted_birthdates = birthdates.shift(15, freq=pd.datetools.day) 

和類似的小時,如果你想。在這個SO question和相關的pandas github issue的答案中也有有用的信息。

+0

是的,這很好。謝謝! –