简体   繁体   中英

How to create MultiIndex DataFrame from other pandas DataFrames

I have basically two DataFrames from different dates and want to join them into one

let's say this is data from 25 Sep

hour    columnA  columnB
0       12       24
1       45       87
2       10       58
3       12       13
4       12       20

here is data from 26sep

hour    columnA  columnB
0       54       89
1       45       3
2       33       97
3       12       13
4       78       47

now I want to join both DataFrames and get MultiIndex DataFrame like this

25sep hour  columnA  columnB
        0       12       24
        1       45       87
        2       10       58
        3       12       13
        4       12       20
26sep hour  columnA  columnB
        0       54       89
        1       45       3
        2       33       97
        3       12       13
        4       78       47

I read the docs about MultiIndex but am not sure how to apply it to my situation.

Use pandas.concat

https://pandas.pydata.org/docs/reference/api/pandas.concat.html

>>> df = pd.concat([df1.set_index('hour'), df2.set_index('hour')],
                   keys=["25sep", "26sep"])
>>> df

            columnA  columnB
      hour                  
25sep 0          12       24
      1          45       87
      2          10       58
      3          12       13
      4          12       20
26sep 0          54       89
      1          45        3
      2          33       97
      3          12       13
      4          78       47

Let us try

out = pd.concat({ y : x.set_index('hour') for x, y  in zip([df1,df2],['25sep','26sep'])})
            columnA  columnB
      hour                  
25sep 0          12       24
      1          45       87
      2          10       58
      3          12       13
      4          12       20
26sep 0          54       89
      1          45        3
      2          33       97
      3          12       13
      4          78       47

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