'index'对象没有属性'tz_localize'

时间:2015-03-06 16:40:16

标签: python pandas

我正在尝试在csv文件中的时间/日期列('Created_At')中转换'GMT'时间的所有实例,以便它全部格式化为'EST'。 请参阅以下内容:

import pandas as pd
from pandas.tseries.resample import TimeGrouper
from pandas.tseries.offsets import DateOffset
from pandas.tseries.index import DatetimeIndex

cambridge = pd.read_csv('\Users\cgp\Desktop\Tweets.csv')
cambridge['Created_At'] = pd.to_datetime(pd.Series(cambridge['Created_At']))
cambridge.set_index('Created_At', drop=False, inplace=True)
cambridge.index = cambridge.index.tz_localize('GMT').tz_convert('EST')
cambridge.index = cambridge.index - DateOffset(hours = 12)

我得到的错误是:

cambridge.index = cambridge.index.tz_localize('GMT').tz_convert('EST')
  

AttributeError:'Index'对象没有属性'tz_localize'

我尝试了各种不同的东西,但我很难过为什么Index对象无法识别tz_attribute。非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

嗯。像其他tz_localize当前问题一样,这对我来说很好。这对你有用吗?我从你的例子中简化了一些调用:

df2 =  pd.DataFrame(randn(3, 3), columns=['A', 'B', 'C'])
# randn(3,3) returns nine random numbers in a 3x3 array.
# the columns argument to DataFrame names the 3 columns. 
# no datetimes here! (look at df2 to check)

df2['A'] = pd.to_datetime(df2['A'])
# convert the random numbers to datetimes -- look at df2 again
# if A had values to_datetime couldn't handle, we'd clean up A first

df2.set_index('A',drop=False, inplace=True)
# and use that column as an index for the whole df2;

df2.index  = df2.index.tz_localize('GMT').tz_convert('US/Eastern')
# make it timezone-conscious in GMT and convert that to Eastern

df2.index.tzinfo
<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>

答案 1 :(得分:0)

替换

cambridge.set_index('Created_At', drop=False, inplace=True)

cambridge.set_index(pd.DatetimeIndex(cambridge['Created_At']), drop=False, inplace=True)