I'm sure this question must have already been answered somewhere but I couldn't find an answer that suits my case.
I have 2 pandas DataFrames

a = pd.DataFrame({'A1':[1,2,3], 'A2':[2,4,6]}, index=['a','b','c'])
b = pd.DataFrame({'A1':[3,5,6], 'A2':[3,6,9]}, index=['a','c','d'])

我想合并它们以获得类似的结果

result = pd.DataFrame({
    'A1' : [3,2,5,6],
    'A2' : [3,4,6,9]
}, index=['a','b','c','d'])

Basically, I want a new df with the union of both indexes. Where indexes match, the value in each column should be updated with the one from the second df (in this case b). Where there is no match the value is taken from the starting df (in this case a).
I tried with merge(), join() and concat() but I could not manage to obtain this result.

推荐答案

如果 comments 是正确的,并且结果中确实有输入错误,那么可以使用pd.concat创建一个数据帧(b是第一个,因为b的优先级高于a),然后删除重复的索引:

使用示例数据:

c = pd.concat([b,a])
c[~c.index.duplicated()].sort_index()

输出:

   A1  A2
a   3   3
b   2   4
c   5   6
d   6   9

Python相关问答推荐

如何在Pandas 中存储二进制数?

Python无法在已导入的目录中看到新模块

如何防止Plotly在输出到PDF时减少行中的点数?

从DataFrame.apply创建DataFrame

在函数内部使用eval(),将函数的输入作为字符串的一部分

提取两行之间的标题的常规表达

try 与gemini-pro进行多轮聊天时出错

试图找到Python方法来部分填充numpy数组

根据在同一数据框中的查找向数据框添加值

如何在箱形图中添加绘制线的传奇?

try 在树叶 map 上应用覆盖磁贴

' osmnx.shortest_track '返回有效源 node 和目标 node 的'无'

对所有子图应用相同的轴格式

如何获得每个组的时间戳差异?

将tdqm与cx.Oracle查询集成

如果值发生变化,则列上的极性累积和

如何从pandas的rame类继承并使用filepath实例化

python panda ExcelWriter切换动态公式到数组公式

ModuleNotFoundError:没有模块名为x时try 运行我的代码''

如何根据rame中的列值分别分组值