Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas : how to transform multi select column to index / column

Tags:

python

pandas

I have a dataframe looking like that :

    2023-12-31          2024-01-31
   myvalue1   myvalue2  myvalue1    myvalue2
a   2          6          2           6
b   3          7          3           7
c   4          8          4           8

which can be created by :

df = pd.DataFrame(index=['a', 'b', 'c'], data=
                   {'myvalue1':[2,3, 4], 'myvalue2':[6,7,8]})\
      .reindex(['myvalue1', 'myvalue2'] * 2, axis=1) \
        .set_axis(pd.MultiIndex.from_product([['2023-12-31','2024-01-31'], ['myvalue1', 'myvalue2']]), axis=1)

How can I get the sum in each column in the following format :

                myvalue1      myvalue2  
2023-12-31         9           21
2024-01-31         9           21

Note that this is only the example where pair of columns are the same.

Thank you

like image 406
Nicolas Avatar asked Nov 18 '25 15:11

Nicolas


1 Answers

sum the rows and reshape with unstack:

out = df.sum().unstack()

Output:

            myvalue1  myvalue2
2023-12-31         9        21
2024-01-31         9        21
like image 182
mozway Avatar answered Nov 21 '25 04:11

mozway