python - 合并多个数据框pandas

标签 python pandas merge

我尝试将多个新数据帧合并到一个主数据帧中。 假设主数据框:

      key1           key2
0   0.365803    0.259112
1   0.086869    0.589834
2   0.269619    0.183644
3   0.755826    0.045187
4   0.204009    0.669371

我尝试将以下 2 个数据集合并到主数据集中,
新数据1:

        key1    key2    new feature
0   0.365803    0.259112    info1

新数据2:

        key1    key2    new feature
0   0.204009    0.669371    info2

预期结果:

       key1       key2  new feature
0   0.365803    0.259112    info1
1   0.776945    0.780978    NaN
2   0.275891    0.114998    NaN
3   0.667057    0.373029    NaN
4   0.204009    0.669371    info2

我尝试过的:

test = test.merge(data1, left_on=['key1', 'key2'], right_on=['key1', 'key2'], how='left')
test = test.merge(data2, left_on=['key1', 'key2'], right_on=['key1', 'key2'], how='left')

对于第一个效果很好,但对于第二个效果不佳,我得到的结果:

        key1    key2    new feature_x   new feature_y
0   0.365803    0.259112    info1      NaN
1   0.776945    0.780978    NaN        NaN
2   0.275891    0.114998    NaN        NaN
3   0.667057    0.373029    NaN        NaN
4   0.204009    0.669371    NaN       info2

感谢您的帮助!

最佳答案

第一appendconcat两个DataFrame在一起,然后合并:

dat = pd.concat([data1, data2], ignore_index=True)

或者:

dat = data1.append(data2, ignore_index=True)

print (dat)
       key1      key2 new feature
0  0.365803  0.259112       info1
1  0.204009  0.669371       info2

#if same joined columns names better is only on parameter
df = test.merge(dat, on=['key1', 'key2'], how='left')

print (df)
       key1      key2 new feature
0  0.365803  0.259112       info1
1  0.086869  0.589834         NaN
2  0.269619  0.183644         NaN
3  0.755826  0.045187         NaN
4  0.204009  0.669371       info2

关于python - 合并多个数据框pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51115262/

相关文章:

python - 如何测试美丽汤对象的类型?

python 如何获取导入包中运行脚本的文件名

Mercurial 手动 merge 不会启动 meld

algorithm - 为什么 Merge Sort 的 Merge() 函数有条件第二个循环?

python - Pandas - 在多列上有条件地合并数据框

python - Kubernetes CronJob 运行 Python 脚本

python - Pandas 绘制 Timedelta 系列,在选定时间使用垂直线

python - 使用 np.where 将列值转换为 NaN

python - 如果字符串存在于列表中,则替换整个数据框中的字符串

python - 请解释 tkinter 全局导入方法的基本原理