0

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.