[英]Stack/Join/Merge two different DataFrame of different numbers of rows & columns
Input输入
Df1: DF1:
A B C
a 2 4 4
b 1 6 3
c 4 2 8
Df2: 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.我想将
Df1
和Df2
彼此相连,如上图所示。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.