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

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

python - Combine multiple pandas DataFrames into a multi-index DataFrame

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

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

1 Answer

0 votes
by (71.8m points)

IIUC

l=[DF1,DF2,DF3]

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...