for multiindex for columns calculate min/max of columns that share the same name for level=1

Question:

Good day,
For the following dataframe with MultiIndex for columns

      1    |    2   |     level = 1
--------------------
   a |  b | a | b |   level = 0
------------------
0  1     2    3   1  
1  2     5    6   4
2  85    74   5   92

I am trying to caclulate min and max of columns for level = 1 (max/min of columns a and b for column 1 and max/min of columns a and b for column 2), but have not find the decent way to do it.

I would like to have something like this:

        1    |    2   |     level = 1
-----------------------
      a |  b | a | b  |   level = 0
-----------------------
min    1         1
max    85        92

Could you help me and share your ideas please.

Asked By: starikovmax

||

Answers:

You can stack the unused level (1, not 0!) and agg:

out = df.stack().agg(['min', 'max'])

Output:

      1   2
min   1   1
max  85  92

Reproducible input:

df = pd.DataFrame([[1,2,3,1],[2,5,6,4],[85,74,5,92]],
                 columns=pd.MultiIndex.from_product([[1, 2], ['a', 'b']])
                 )
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.