Python AttributeError: 'DataFrame' 对象没有属性 'to_datetime'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48387878/
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
AttributeError: 'DataFrame' object has no attribute 'to_datetime'
提问by Mona Jalal
I want to convert all the items in the 'Time' column of my pandas dataframe from UTC to Eastern time. However, following the answer in this stackoverflowpost, some of the keywords are not known in pandas 0.20.3. Overall, how should I do this task?
我想将 Pandas 数据帧的“时间”列中的所有项目从 UTC 转换为东部时间。但是,根据此 stackoverflow帖子中的答案,某些关键字在 pandas 0.20.3 中未知。总的来说,我应该如何完成这项任务?
tweets_df = pd.read_csv('valid_tweets.csv')
tweets_df['Time'] = tweets_df.to_datetime(tweets_df['Time'])
tweets_df.set_index('Time', drop=False, inplace=True)
error is:
错误是:
tweets_df['Time'] = tweets_df.to_datetime(tweets_df['Time'])
File "/scratch/sjn/anaconda/lib/python3.6/site-packages/pandas/core/generic.py", line 3081, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'to_datetime'
items from the Time column look like this:
时间列中的项目如下所示:
2016-10-20 03:43:11+00:00
Update: using
更新:使用
tweets_df['Time'] = pd.to_datetime(tweets_df['Time'])
tweets_df.set_index('Time', drop=False, inplace=True)
tweets_df.index = tweets_df.index.tz_localize('UTC').tz_convert('US/Eastern')
did no time conversion. Any idea what could be fixed?
没有时间转换。知道什么可以解决吗?
Update 2: So the following code, does not do in-place conversion meaning when I print the row['Time'] using iterrows() it shows the original values. Do you know how to do the in-place conversion?
更新 2:因此,当我使用 iterrows() 打印 row['Time'] 时,以下代码不会进行就地转换,它显示原始值。你知道如何进行就地转换吗?
tweets_df['Time'] = pd.to_datetime(tweets_df['Time'])
for index, row in tweets_df.iterrows():
row['Time'].tz_localize('UTC').tz_convert('US/Eastern')
for index, row in tweets_df.iterrows():
print(row['Time'])
回答by Alex
to_datetime
is a function defined in pandas not a method on a DataFrame. Try:
to_datetime
是在 Pandas 中定义的函数,而不是 DataFrame 上的方法。尝试:
tweets_df['Time'] = pd.to_datetime(tweets_df['Time'])