pandas “索引”对象没有属性“tz_localize”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28903399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:01:17  来源:igfitidea点击:

'Index' object has no attribute 'tz_localize'

pythonpandas

提问by cgp25

I'm trying to convert all instances of 'GMT' time in a time/date column ('Created_At') in a csv file so that it is all formatted in 'EST'. Please see below:

我正在尝试在 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)

The error I'm getting is:

我得到的错误是:

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

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

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

I've tried various different things but am stumped as to why the Index object won't recognized the tz_attribute. Thank you so much for your help!

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

采纳答案by cphlewis

Hmm. Like the other tz_localize current problem, this works fine for me. Does this work for you? I have simplified some of the calls a bit from your example:

唔。就像其他 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>
<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>

回答by Mostafa Mahmoud

Replace

代替

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

with

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