Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapse pandas multiindex to a single index

I have a multi-indexed Pandas dataframe that looks like this:

enter image description here

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]
    ]
)
like image 400
user217285 Avatar asked Jan 24 '18 21:01

user217285


People also ask

How do I convert MultiIndex to single index in pandas?

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.

How do you flatten a pandas level?

Flatten columns: use get_level_values() Flatten columns: use to_flat_index() Flatten columns: join column labels. Flatten rows: flatten all levels.

How convert MultiIndex to columns in pandas?

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.


1 Answers

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
like image 196
piRSquared Avatar answered Sep 20 '22 23:09

piRSquared