Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have three dataframes with equivalent indices, index names and column names:

DF1:
         value
index
    0       a0
    1       a1
    2       a2
    3       a3

DF2:
         value
index
    0       b0
    1       b1
    2       b2
    3       b3

DF3:
         value
index
    0       c0
    1       c1
    2       c2
    3       c3

I'd like to combine all 3 into a single multi-index dataframe, where the old index is now a column, and the new index is now ['DF1', 'DF2', 'DF3'].

             old_index     value
new_index
      DF1            0        a0
                     1        a1
                     2        a2
                     3        a3
      DF2            0        b0
                     1        b1
                     2        b2
                     3        b3
      DF3            0        c0
                     1        c1
                     2        c2
                     3        c3

What's the easiest way to go about this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
871 views
Welcome To Ask or Share your Answers For Others

1 Answer

IIUC

l=[DF1,DF2,DF3]

pd.concat(l,keys= ['DF1', 'DF2', 'DF3'],axis=0).reset_index(level=1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...