Python 垂直合并2个数据帧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41181779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
merging 2 dataframes vertically
提问by Andrei Cozma
I have 2 dataframes that have 2 columns each (same column names). I want to merge them vertically to end up having a new dataframe.
我有 2 个数据框,每个数据框有 2 列(相同的列名)。我想垂直合并它们以最终拥有一个新的数据框。
When doing
做的时候
newdf = df.merge(df1,how='left',on=['Col1','Col2'])
The new df has only the rows from dfand none of the rows from df1. Any reasons why this might happen?
新的 df 只有来自 的行df,没有来自 的行df1。这可能发生的任何原因?
Col1 Col2
asd 1232
cac 2324
.....
and the df1is:
这df1是:
Col1 Col2
afaf 1213
asas 4353
The new dataframe newdfshould be:
新的数据框newdf应该是:
Col1 Col2
asd 1232
cac 2324
afaf 1213
asas 4353
回答by Zero
You could use appendand use ignore_indexif you don't want to use the index values as is.
如果您不想按原样使用索引值,则可以使用append和使用ignore_index。
In [14]: df1.append(df2)
Out[14]:
Col1 Col2
0 asd 1232
1 cac 2324
0 afaf 1213
1 asas 4353
In [15]: df1.append(df2, ignore_index=True)
Out[15]:
Col1 Col2
0 asd 1232
1 cac 2324
2 afaf 1213
3 asas 4353
or use pd.concat
或使用 pd.concat
In [16]: pd.concat([df1, df2])
Out[16]:
Col1 Col2
0 asd 1232
1 cac 2324
0 afaf 1213
1 asas 4353
In [17]: pd.concat([df1, df2], ignore_index=True)
Out[17]:
Col1 Col2
0 asd 1232
1 cac 2324
2 afaf 1213
3 asas 4353

