简体   繁体   中英

Convert python pandas dataframe into different format

I have a data frame in python and I want to convert in different format :

Below is the example of the same :

Current Data frame :

                  Header 1             Header 1 
              Col_A  Col_B         Col_A       Col_B
2021-07-15     1        2            3         4
2021-07-16     5        6            7         8

Expected Output :

Date        Header_No   Col_A   Col_B
2021-07-15       1          1      2
2021-07-16       1          5      6
2021-07-15       2          3      4
2021-07-16       2          7      8

Basically I want 4 columns Date , Header_No , Col_A, Col_B.

That's literally what .stack() does:

Stack the prescribed level(s) from columns to index.

With some tweaking to rename columns as you want to and from index levels and/or columns:

>>> stacked = df.rename(columns=lambda c: int(c.split()[-1]), level=0).stack(level=0)
>>> stacked
              Col_A  Col_B
2021-07-15 1      1      2
           2      3      4
2021-07-16 1      5      6
           2      7      8
>>> stacked.rename_axis(['Date', 'Header_No']).reset_index()
         Date  Header_No  Col_A  Col_B
0  2021-07-15          1      1      2
1  2021-07-15          2      3      4
2  2021-07-16          1      5      6
3  2021-07-16          2      7      8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM