python - 垂直合并2个数据帧

标签 python pandas merge

<分区>

我有 2 个数据框,每个数据框有 2 列(相同的列名)。我想垂直合并它们以最终得到一个新的数据框。

做的时候

newdf = df.merge(df1,how='left',on=['Col1','Col2'])

新的 df 只有来自 df 的行,没有来自 df1 的行。发生这种情况的任何原因?

Col1    Col2
asd     1232
cac     2324
.....

df1 是:

Col1    Col2
afaf    1213
asas    4353

新数据框 newdf 应该是:

Col1   Col2
asd     1232
cac     2324
afaf    1213
asas    4353

最佳答案

如果您不想按原样使用索引值,则可以使用 appendignore_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

或者使用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

关于python - 垂直合并2个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41181779/

相关文章:

python - 将值列表转换为编码变量?

svn - 手动合并发散代码的技巧

python - 即使使用 1 行/2 列数组,也在 python 中迭代 Numpy 数组行

python - 应用pandas的groupby功能后如何分析数据?

python - 如何查询比较字符串 Pandas

json - 如何通过使用 jq 在键上分组来合并 json 对象

csv - Powershell,使用文件名合并CSV文件

python - 错误 : 'float' object does not support item assignment

python - 将Python 3转换为autodoc可以读取的 "simple"python

python - pgadmin4 - 新安装不工作