2014-09-28 26 views
7

在接下來的一系列時間戳申請方法:無法使用系列內置插件

0 1411161507178 
1 1411138436009 
2 1411123732180 
3 1411167606146 
4 1411124780140 
5 1411159331327 
6 1411131745474 
7 1411151831454 
8 1411152487758 
9 1411137160544 
Name: my_series, dtype: int64 

此命令(轉換爲時間戳,定位和轉換爲美國東部時間)的工作原理:

pd.to_datetime(my_series, unit='ms').apply(lambda x: x.tz_localize('UTC').tz_convert('US/Eastern')) 

這一個失敗:

pd.to_datetime(my_series, unit='ms').tz_localize('UTC').tz_convert('US/Eastern') 

有:

TypeError         Traceback (most recent call last) 
<ipython-input-3-58187a4b60f8> in <module>() 
----> 1 lua = pd.to_datetime(df[column], unit='ms').tz_localize('UTC').tz_convert('US/Eastern') 

/Users/josh/anaconda/envs/py34/lib/python3.4/site-packages/pandas/core/generic.py in tz_localize(self, tz, axis, copy, infer_dst) 
    3492     ax_name = self._get_axis_name(axis) 
    3493     raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' % 
-> 3494         ax_name) 
    3495    else: 
    3496     ax = DatetimeIndex([],tz=tz) 

TypeError: index is not a valid DatetimeIndex or PeriodIndex 

也是如此這個

my_series.tz_localize('UTC').tz_convert('US/Eastern') 

有:

--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-4-0a7cb1e94e1e> in <module>() 
----> 1 lua = df[column].tz_localize('UTC').tz_convert('US/Eastern') 

/Users/josh/anaconda/envs/py34/lib/python3.4/site-packages/pandas/core/generic.py in tz_localize(self, tz, axis, copy, infer_dst) 
    3492     ax_name = self._get_axis_name(axis) 
    3493     raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' % 
-> 3494         ax_name) 
    3495    else: 
    3496     ax = DatetimeIndex([],tz=tz) 

TypeError: index is not a valid DatetimeIndex or PeriodIndex 

據我瞭解,上述(失敗的第一個),第二種方法應該工作。它爲什麼會失敗?

+0

我不知道爲什麼你的第一種方法的工作原理其實,作爲你的第二個錯誤說法是很清楚的,如果你實際上指數的Int64值那麼第二種方法作品。 – EdChum 2014-09-28 21:33:02

回答

5

tz_localize/tz_convert作用於對象的INDEX,而不是數值。最簡單的方法就是將它變成索引,然後進行本地化和轉換。如果再要一個系列回你可以索引,而不是數據使用to_series()

In [47]: pd.DatetimeIndex(pd.to_datetime(s,unit='ms')).tz_localize('UTC').tz_convert('US/Eastern') 
Out[47]: 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2014-09-19 17:18:27.178000-04:00, ..., 2014-09-19 10:32:40.544000-04:00] 
Length: 10, Freq: None, Timezone: US/Eastern 
14

傑夫的回答中提到,tz_localize()tz_convert()行爲。這對我來說也是一個巨大的驚喜。

自從傑夫的答案被寫入,Pandas 0.15添加了一個新的Series.dt訪問器,可以幫助您的用例。現在,你可以這樣做:

pd.to_datetime(my_series, unit='ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern') 
+0

這太棒了!我不希望將TimeStamp設置爲索引,有時,我們可能會有兩個TimeStamp,因爲我們必須將其轉換爲索引,這實在令人沮喪。 – user40780 2017-06-26 01:48:15