【问题标题】:How to append two dataframes in python pandas [duplicate]如何在python pandas中附加两个数据框[重复]
【发布时间】:2021-11-08 14:32:23
【问题描述】:
我正在处理一个成人数据集,我在其中拆分数据框以标记编码分类列。现在我想用原始数据框附加新的数据框。执行相同操作的最简单方法是什么?
原始数据框-
| age |
salary |
| 32 |
3000 |
| 25 |
2300 |
标签编码几列后
我想追加上面的dataframe,最终结果应该如下。
| age |
salary |
country |
gender |
| 32 |
3000 |
1 |
1 |
| 25 |
2300 |
4 |
2 |
任何见解都会有所帮助。
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
让我们考虑两个名为 df1 和 df2 的数据框,
df1.merge(df2,left_index=True, right_index=True)
【解决方案2】:
如果 datrframes 行通过索引匹配,您可以使用.join(),如下所示:
.join() 默认为左连接,按索引连接。
df1.join(df2)
除了简单的语法之外,它还有一个额外的优势,即当您将主/原始数据框放在左侧时,左连接可确保在结果中保留主数据框的索引。
结果:
age salary country gender
0 32 3000 1 1
1 25 2300 4 2
【解决方案3】:
您可能会在检查pandas.concat 中找到您的解决方案。
import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.array([[32,3000],[25,2300]]), columns=['age', 'salary'])
df2 = pd.DataFrame(np.array([[1,1],[4,2]]), columns=['country', 'gender'])
pd.concat([df1, df2], axis=1)
age salary country gender
0 32 25 1 1
1 3000 2300 4 2