clog14
clog14

Reputation: 1641

Convert pandas multiindex to datetime format

I have a multiindex in pandas that looks like the one generated by the following code:

arrays = [[2001, 2001, 2003, 2004], ['January', 'March', 'June', 'December']]
tuples= list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['year', 'month'])

I would like to convert this index to a single datetime index. I tried using

pd.to_datetime(index, format="%Y %B")

but it gives me an error.

Can you please provide some help on how to accomplish this in the most efficient way?

Thanks

Upvotes: 2

Views: 1585

Answers (1)

jezrael
jezrael

Reputation: 862481

You can use map first:

idx = index.map(lambda x: ''.join((str(x[0]), x[1])))
print (idx)
['2001January' '2001March' '2003June' '2004December']

print (pd.to_datetime(idx, format="%Y%B"))
DatetimeIndex(['2001-01-01', '2001-03-01', '2003-06-01', '2004-12-01'],
               dtype='datetime64[ns]', freq=None)

Another solution:

idx = index.map(lambda x: '{}{}'.format(x[0], x[1]))
print (idx)
['2001January' '2001March' '2003June' '2004December']

Or list comprehension solution:

idx = ['{}{}'.format(x[0], x[1]) for x in index]
print (idx)
['2001January', '2001March', '2003June', '2004December']

Upvotes: 2

Related Questions