Pandas DatetimeIndex将日期转换为1970

时间:2016-07-20 14:37:36

标签: python datetime pandas dataframe python-datetime

我最近遇到了类似的问题(answered here),其中使用这些日期将日期转换为pandas DatetimeIndex和后续groupby会导致错误,其中日期显示为{ {1}}。

我现在在不同的背景下面对这个问题,之前的解决方案并没有帮助我。

我有这样的框架

1970-01-01 00:00:00+00:00

我希望将索引从日期更改为import pandas as pd from dateutil import tz data = { 'Events' : range(1, 5 + 1 ,1), 'ID' : [1, 1, 1, 1, 1]} idx = pd.date_range(start='2008-01-01', end='2008-01-05', freq='D', tz=tz.tzlocal()) frame = pd.DataFrame(data, index=idx) Events ID 2008-01-01 00:00:00+00:00 1 1 2008-01-02 00:00:00+00:00 2 1 2008-01-03 00:00:00+00:00 3 1 2008-01-04 00:00:00+00:00 4 1 2008-01-05 00:00:00+00:00 5 1 的{​​{3}},但这样做会导致" 1970错误"出现

[date, ID]

版本

  • Python 2.7.11
  • Pandas 0.18.0

2 个答案:

答案 0 :(得分:1)

你的另一个问题的接受答案对我有用(Python 3.5.2,Pandas 0.18.1):

print(frame.set_index([frame.ID, frame.index]))

#                               Events  ID
# ID                                      
# 1  2008-01-01 00:00:00-05:00       1   1
#    1970-01-01 00:00:00-05:00       2   1
#    1970-01-01 00:00:00-05:00       3   1
#    1970-01-01 00:00:00-05:00       4   1
#    1970-01-01 00:00:00-05:00       5   1

frame.index = frame.index.tz_convert(tz='EST')
print(frame.set_index([frame.ID, frame.index]))

#                               Events  ID
# ID                                      
# 1  2008-01-01 00:00:00-05:00       1   1
#    2008-01-02 00:00:00-05:00       2   1
#    2008-01-03 00:00:00-05:00       3   1
#    2008-01-04 00:00:00-05:00       4   1
#    2008-01-05 00:00:00-05:00       5   1

(我当地的时间与你的不同。)

答案 1 :(得分:1)

frame = frame.reset_index()
frame = frame.set_index([frame.ID, frame.index])
print frame

                         index  Events  ID
ID                                        
1  0 2008-01-01 00:00:00-05:00       1   1
   1 2008-01-02 00:00:00-05:00       2   1
   2 2008-01-03 00:00:00-05:00       3   1
   3 2008-01-04 00:00:00-05:00       4   1
   4 2008-01-05 00:00:00-05:00       5   1


print frame.info()

<class 'pandas.core.frame.DataFrame'>
MultiIndex: 5 entries, (1, 0) to (1, 4)
Data columns (total 4 columns):
level_0    5 non-null int64
index      5 non-null datetime64[ns, tzlocal()]
Events     5 non-null int64
ID         5 non-null int64
dtypes: datetime64[ns, tzlocal()](1), int64(3)
memory usage: 200.0+ bytes