Search code examples
pythonpandasdataframemulti-index

How to change a Pandas DataFrame into a column Multi-Column?


I have a Pandas DataFrame with a column index like the one below:

+----+----+----+----+----+----+
|  A1|  A2|  A3|  B1|  B2|  B3|
+----+----+----+----+----+----+
...the data

What I would like to do is to change the column index of this DataFrame to a multi-index one, as shown in the format below, without modifying the data and just simply adding an upper level in the index (with values A and B).

+--------------+--------------+
|        A     |        B     |
+----+----+----+----+----+----+
|  A1|  A2|  A3|  B1|  B2|  B3|
+----+----+----+----+----+----+
...the data

I have tried to use the pandas.MultiIndex function but with no luck. How can this be solved?


Solution

  • You could extract the first letter separately and create a MultiIndex -

    multi_index_level_0 = [c[0] for c in df.columns]
    multi_index = [multi_index_level_0, df.columns.values]
    df.columns = pd.MultiIndex.from_arrays(multi_index)