熊猫AttributeError:“ DataFrame”对象没有属性“ Datetime”

时间:2018-09-05 10:00:09

标签: python pandas dataframe

我正在采用冬冬季方法服用help from here。我的数据格式是

 Year       Rate
0  2013  34.700000
1  2013  34.666667
2  2013  34.600000
3  2014  35.300000
4  2014  34.180000

下面是我的代码

import pandas as pd 

#Importing data

df = pd.read_csv('/home/rajnish.kumar/eclipse-workspace/ShivShakti/Result/weeklyDatarateyearonly/part-00000-971f46d7-a97d-4a7e-be41-dc840c2d0618-c000.csv')

df.Timestamp = pd.to_datetime(df.Datetime,format='%Y') 

但是我收到此错误:

  

AttributeError:“ DataFrame”对象没有属性“ Datetime”

2 个答案:

答案 0 :(得分:1)

如果您的数据确实如图所示(带有RateYear列),则表示您引用的列(Datetime)不存在(与链接的博客文章(确实有这样的专栏):

import pandas as pd
data = {'Year':[2013, 2013, 2013, 2014, 2014], 'Rate':[34.7, 34.6,34.6,35.3,34.18]}
df = pd.DataFrame(data, columns=["Year", "Rate"])
df.Timestamp = pd.to_datetime(df.Datetime,format='%Y') 
# AttributeError: 'DataFrame' object has no attribute 'Datetime'

您应改为引用Year

df['Timestamp'] = pd.to_datetime(df['Year'],format='%Y') 
df
# result:
   Year   Rate  Timestamp
0  2013  34.70 2013-01-01
1  2013  34.60 2013-01-01
2  2013  34.60 2013-01-01
3  2014  35.30 2014-01-01
4  2014  34.18 2014-01-01

答案 1 :(得分:0)

你可以使用这样的东西:

import pandas as pd
data = {'Year':[2013, 2013, 2013, 2014, 2014], 'Rate':[34.7, 34.6,34.6,35.3,34.18]}
df = pd.DataFrame(data, columns=["Year", "Rate"])
df.Timestamp = pd.to_datetime(df.Year)