Reputation: 22001
I have the foll. dataframe:
col_a col_b
4 15 69.717679 0.09701
16 69.717679 0.09701
17 69.717679 0.09701
18 69.717679 0.09701
19 69.717679 0.09701
It has a multi-index with the first level representing the month(4) and the next level representing the day of the month (1..31). How do I convert the multilevel index to a datetime index? The year value is 2013.
I tried this:
pd.to_datetime(df_past.index.levels[1] + df_past.index.levels[0] + 2013, format="%d%m%Y")
but get the error:
*** ValueError: cannot evaluate a numeric op with unequal lengths
Upvotes: 1
Views: 911
Reputation: 109636
The following list comprehension/zip method will get you the dates as datetime objects.
import datetime as dt
new_index = [dt.datetime(2013, month, day)
for month, day in zip(*[df.index.get_level_values(i) for i in (0, 1)])]
Upvotes: 1
Reputation: 139222
To get the values of a level of the index, you need .get_level_values()
instead of .levels
:
pd.to_datetime(2013 * 10000 + df_past.index.get_level_values(0) * 100 +
df_past.index.get_level_values(1), format="%Y%m%d")
Further, if you add those as integer values, you need to multiply with 10000/100 to get the correct format. An alternative is to astype(str)
each of them, and then just adding (concatenating) will work.
Upvotes: 4