Folarin
Folarin

Reputation: 21

Pandas: converting int64 years to datetime dsiplaying only the year

I have a dataframe index that looks like this:

df.index
Int64Index([1992, 1993, 1994, 1995], dtype='int64')

but would like it converted to datetime whilst only displaying the year thereby preserving the above yearly format.

I have tried: Pandas: how to convert an index of int64 years to datetime

import pandas as pd
df.index = pd.to_datetime(df.index, format='%Y')

but this gives me:

DatetimeIndex(['1992-01-01', '1993-01-01', '1994-01-01', '1995-01-01'], dtype='datetime64[ns]', freq=None)

Instead is there a better way I can get something along the lines of:

DatetimeIndex(['1992', '1993', '1994', '1995'], dtype='datetime64)

Upvotes: 2

Views: 3027

Answers (3)

Ahmed_ElKodsh
Ahmed_ElKodsh

Reputation: 1

I found this to be useful

df.index = pd.to_datetime(df.index, format='%Y').year

Upvotes: -1

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210872

What about PeriodIndex?

In [131]: i = pd.Int64Index([1992, 1993, 1994, 1995], dtype='int64')

In [132]: pd.PeriodIndex(i, freq='A')
Out[132]: PeriodIndex(['1992', '1993', '1994', '1995'], dtype='period[A-DEC]', freq='A-DEC')

Upvotes: 2

jezrael
jezrael

Reputation: 862851

Use PeriodIndex, because is not possible create DatetimeIndex without months and days:

idx = pd.Int64Index([1992, 1993, 1994, 1995])
print (idx)
Int64Index([1992, 1993, 1994, 1995], dtype='int64')

per = pd.PeriodIndex(idx, freq='A')
print (per)
PeriodIndex(['1992', '1993', '1994', '1995'], dtype='period[A-DEC]', freq='A-DEC')

Upvotes: 3

Related Questions