I have multi-index df as follows
x y
id date
abc 3/1/1994 100 7
9/1/1994 90 8
3/1/1995 80 9
Where dates are stored as str.
I want to parse date index. The following statement
df.index.levels[1] = pd.to_datetime(df.index.levels[1])
returns error:
TypeError: 'FrozenList' does not support mutable operations.
An easy way to do this is via Pandas’ multi-indexing functionality. If you run the following line of code on our data above (stored in the dataframe called data ), it creates a multi-index for data. We’ve chosen to index by both stock ticker and date, hence multi-indexing because we are indexing by more than one column.
We used the to_datetime method available in Pandas to parse the day, month and year columns into a single date column. We can drop the first three columns as they are redundant. Further, we can check attributes’ data types . forestfire.drop (columns= ['day','month','year'], inplace=True) forestfire.info ()
To convert the index of a DataFrame to DatetimeIndex, use Pandas' to_datetime (~) method.
Optional datetime-like data to construct index with. One of pandas date offset strings or corresponding objects. The string ‘infer’ can be passed in order to set the frequency of the index as the inferred frequency upon creation. Set the Timezone of the data. Normalize start/end dates to midnight before generating date range.
As mentioned, you have to recreate the index:
df.index = df.index.set_levels([df.index.levels[0], pd.to_datetime(df.index.levels[1])])
You cannot modify it in-place. You can use pandas.MultiIndex.map to create a new index and then assign it:
new_tuples = df.index.map(lambda x: (x[0], pd.to_datetime(x[1])))
df.index = pd.MultiIndex.from_tuples(new_tuples, names=["id", "date"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With