Home > Net >  How to create MultiIndex DataFrame from other pandas DataFrames
How to create MultiIndex DataFrame from other pandas DataFrames

Time:10-28

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related