简体   繁体   中英

Stack/Join/Merge two different DataFrame of different numbers of rows & columns

Input
Df1:

    A    B    C
a   2    4    4
b   1    6    3
c   4    2    8

Df2:

P    Q    R    S    T
5    3    8    3    0
4    8    6    8    3

Desired Output

    A    B    C
a   2    4    4
b   1    6    3
c   4    2    8
P    Q    R    S    T
5    3    8    3    0
4    8    6    8    3

I want to connect Df1 and Df2 one below each other as shown above.
How can I do that?

Not sure why you need it, but the code below will make the trick:


import pandas as pd

# initialize dataframes
df1 = pd.DataFrame([[2, 4, 4], [1, 6, 3], [4, 2, 8]],
                   columns=['A', 'B', 'C'], index=['a', 'b', 'c'])

df2 = pd.DataFrame([[3, 8, 3, 0], [8, 6, 8, 3]],
                   columns=['Q', 'R', 'S', 'T'], index=[5, 4])
df2.index.name = 'P'

# prepare for concat
df2.loc[df2.index.name] = df2.columns
df2.index = df2.index.astype(str)
df2 = df2.sort_index(ascending=False)
df2.columns = ['A', 'B', 'C', '']
df2.index.name = ''

df1[''] = ['','','']


# concat
df = pd.concat([df1, df2])

Output:

In [2]: df1
Out[2]: 
   A  B  C  
a  2  4  4  
b  1  6  3  
c  4  2  8  

In [3]: df2
Out[3]: 
   A  B  C   
             
P  Q  R  S  T
5  3  8  3  0
4  8  6  8  3

In [4]: df
Out[4]: 
   A  B  C   
a  2  4  4   
b  1  6  3   
c  4  2  8   
P  Q  R  S  T
5  3  8  3  0
4  8  6  8  3

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