2014-09-28 25 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