Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning columns to a hierarchical higher Multiindex level

I have a dataframe that looks somewhat like this:

   Ax  Ay  Bx  By
0   1  20   2  20
1   3  21   5  22
2   4  20   7  25

and I want to manually define that Ax and Ay have the hierarchical higher MultiIndex level of A (and also do the same for B). So that the dataframe looks like this:

   A      B
   x   y  x   y
0  1  20  2  20
1  3  21  5  22
2  4  20  7  25

So what I'm looking for is a statement that says:

Ax and Ay go under A as x and y

like image 444
Tobias Avatar asked Dec 08 '25 14:12

Tobias


1 Answers

You can manually construct a pandas.MultiIndex using one of several constructors. From the docs:

  • MultiIndex.from_arrays
    Convert list of arrays to MultiIndex.

  • MultiIndex.from_product
    Create a MultiIndex from the cartesian product of iterables.

  • MultiIndex.from_tuples
    Convert list of tuples to a MultiIndex.

  • MultiIndex.from_frame
    Make a MultiIndex from a DataFrame.

All of these are useful and I'd check them each out to understand their use cases. For your case, I think pd.MultiIndex.from_tuples might do the trick:

In [4]: list_of_split_tuples = list(map(tuple, df.columns.values))

In [5]: df.columns = pd.MultiIndex.from_tuples(list_of_split_tuples)

In [6]: df
Out[6]:
   A      B
   x   y  x   y
0  1  20  2  20
1  3  21  5  22
2  4  20  7  25
like image 199
Michael Delgado Avatar answered Dec 10 '25 05:12

Michael Delgado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!