2016-03-12 116 views
1

我有數據幀像這樣熊貓年 - 月格式爲timestamp

2015-01 
2015-02 
2015-03 
2015-04 
2015-05 

時間指數現在我想將它們轉換爲時間戳,這樣

2015-01-31 00:00:00 
2015-02-28 00:00:00 
2015-03-31 00:00:00 
2015-04-30 00:00:00 
2015-05-31 00:00:00 

如何轉換呢?我嘗試過這樣的事情,但它需要幾天,我沒有。

import pandas as pd 
import datetime as dt 
df.index = [dt.datetime(d.year, d.month) for d in df.index] 
`TypeError`: Required argument 'day' (pos 3) not found 

非常感謝!

回答

0

我覺得你可以先嚐試轉換to_datetime然後添加MonthEnd()

print df 
     a 
2015-01 1 
2015-02 2 
2015-03 2 
2015-04 3 
2015-05 4 

print df.index 
PeriodIndex(['2015-01', '2015-02', '2015-03', '2015-04', '2015-05'], dtype='int64', freq='M') 

df.index = df.index.to_datetime() 
print df.index 
DatetimeIndex(['2015-01-01', '2015-02-01', '2015-03-01', '2015-04-01', 
       '2015-05-01'], 
       dtype='datetime64[ns]', freq='MS') 

df.index = df.index + pd.offsets.MonthEnd() 
print df.index 
DatetimeIndex(['2015-01-31', '2015-02-28', '2015-03-31', '2015-04-30', 
       '2015-05-31'], 
       dtype='datetime64[ns]', freq='M') 

print df 
      a 
2015-01-31 1 
2015-02-28 2 
2015-03-31 2 
2015-04-30 3 
2015-05-31 4 
+0

它是如何工作的? – jezrael

+0

非常感謝,它有助於 – GrumpyJun

0

你確定你想要的時間是00:00:00?那將是午夜,在這個月的倒數第二天和最後一天之間

months = pd.Series(['2015-01', '2015-02', '2015-03', '2015-04', '2015-05']) 
>>> [pd.Period(m, 'M').end_time for m in months] 

[Timestamp('2015-01-31 23:59:59.999999999'), 
Timestamp('2015-02-28 23:59:59.999999999'), 
Timestamp('2015-03-31 23:59:59.999999999'), 
Timestamp('2015-04-30 23:59:59.999999999'), 
Timestamp('2015-05-31 23:59:59.999999999')] 
+0

嗯,我從來沒有想過這個,它可能會更好 – GrumpyJun