I have a multi-indexed Pandas dataframe that looks like this:
How can I merge the three-tiered index into one index? Namely, I want to turn (1987, 1, 2) into pd.datetime(1987, 1, 2). I'd prefer a vectorized approach using df.index.map. Here's code that can create the top part of the dataframe:
df = pd.DataFrame(
{'3 months': [1, 2, 3, 4, 5]},
index=[
[1987, 1987, 1987, 1987,1987],
[1,1,1,1,1],
[2,5,6,7,8]
]
)
To revert the index of the dataframe from multi-index to a single index using the Pandas inbuilt function reset_index(). Returns: (Data Frame or None) DataFrame with the new index or None if inplace=True.
Flatten columns: use get_level_values() Flatten columns: use to_flat_index() Flatten columns: join column labels. Flatten rows: flatten all levels.
pandas MultiIndex to Columns Use pandas DataFrame. reset_index() function to convert/transfer MultiIndex (multi-level index) indexes to columns. The default setting for the parameter is drop=False which will keep the index values as columns and set the new index to DataFrame starting from zero.
Simplest solution with pd.Index.map
df.set_index(df.index.map(lambda t: pd.datetime(*t)))
3 months
1987-01-02 1
1987-01-05 2
1987-01-06 3
1987-01-07 4
1987-01-08 5
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