Home > database >  Error while trying to use get .year from an column
Error while trying to use get .year from an column

Time:12-08

When I'm trying to get all years from by database, Python throws an error:

df = pd.to_datetime(df.index)
df['year'] = [i.year for i in df.index]

Output:

AttributeError: 'DatetimeIndex' object has no attribute 'index'

CodePudding user response:

Use DatetimeIndex.year:

df['year'] = pd.to_datetime(df.index).year

In your solution assign back df.index:

df.index = pd.to_datetime(df.index)
df['year'] = [i.year for i in df.index]
  • Related