2017-03-28 80 views
1

考慮這個簡單的例子熊貓:attribute_error轉換時間戳EST

idx2=[pd.to_datetime('2016-08-31 22:08:12') , 
    pd.to_datetime('2016-08-31 22:08:12'), 
    pd.to_datetime(np.NaN)] 

test2=pd.DataFrame({'value':[1,1,3], 'groups' : ['A',np.NaN,'A']},index=idx2) 
test2.reset_index(inplace = True) 


test2 
Out[29]: 
       index groups value 
0 2016-08-31 22:08:12  A  1 
1 2016-08-31 22:08:12 NaN  1 
2     NaT  A  3 

我想列index轉換爲EST,但這

test2['index'].map(lambda x: x.tz_localize('UTC').tz_convert('US/Eastern').tz_localize(None)) 

給我

AttributeError: 'NaTType' object has no attribute 'tz_localize'

使用x[x.notnull()]也不起作用。我能做什麼?

回答

2

無需使用reset_index,而不只是直接在具有tz_localizeDatetimeIndextz_convert運行內置:

test2.index = test2.index.tz_localize('UTC').tz_convert('US/Eastern').tz_localize(None) 

輸出結果:

    groups value 
2016-08-31 18:08:12  A  1 
2016-08-31 18:08:12 NaN  1 
NaT      A  3 

正如@DSM指出,如果您想在列上執行此操作,則可以使用.dt訪問器,但需要在每個時區操作之前使用3個實例.dt

test2.reset_index(inplace=True) 
test2['index'] = test2['index'].dt.tz_localize('UTC').dt.tz_convert('US/Eastern').dt.tz_localize(None) 

       index groups value 
0 2016-08-31 18:08:12  A  1 
1 2016-08-31 18:08:12 NaN  1 
2     NaT  A  3 
+2

即使OP使用'reset_index',他也可以使用'.dt'來獲取方法。 – DSM

+0

謝謝,但我需要做一個列,而不是索引。這也可以正常工作,不需要... –

+1

已更新,以顯示在一列上完成的過程。 – root