[英]How to merge two dataframes row wise in pandas
I want to concatenate my two dataframes (df1 and df2) row wise to obtain dataframe (df3) in below format:我想逐行连接我的两个数据帧(df1 和 df2)以获得 dataframe(df3),格式如下:
1st row of df3 have 1st row of df1. df3 的第一行有 df1 的第一行。
2nd row of df3 have 1st row of df2. df3 的第 2 行有 df2 的第 1 行。
3rd row of df3 have 2nd row of df1. df3 的第 3 行有 df1 的第 2 行。
4th row of df3 have 2nd row of df2. df3 的第 4 行有 df2 的第 2 行。 .. and so on
.. 等等
Any idea how can I do that?知道我该怎么做吗?
Note - both dataframes have same column names注意- 两个数据框具有相同的列名
A simple way would be modifying the index for dataframes before concatenation, then sort on it!一种简单的方法是在连接之前修改数据帧的索引,然后对其进行排序!
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "C2", "C3"],
"D": ["D0", "D1", "D2", "D3"],
},
index=[0, 2, 4, 6],
)
df2 = pd.DataFrame(
{
"A": ["A4", "A5", "A6", "A7"],
"B": ["B4", "B5", "B6", "B7"],
"C": ["C4", "C5", "C6", "C7"],
"D": ["D4", "D5", "D6", "D7"],
},
index=[1, 3, 5, 7],
)
pd.concat((df1, df2)).sort_index(axis = 0)
output: output:
A B C D
0 A0 B0 C0 D0
1 A4 B4 C4 D4
2 A1 B1 C1 D1
3 A5 B5 C5 D5
4 A2 B2 C2 D2
5 A6 B6 C6 D6
6 A3 B3 C3 D3
7 A7 B7 C7 D7
You can use pandas.concat
, and sort_index
:您可以使用
pandas.concat
和sort_index
:
df1 = pd.DataFrame({'col': list('AXYZ')})
df2 = pd.DataFrame({'col': list('EDCB')})
(pd.concat([df1, df2])
.sort_index()
)
Output: Output:
col
0 A
0 E
1 X
1 D
2 Y
2 C
3 Z
3 B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.