【发布时间】:2021-05-11 16:35:14
【问题描述】:
我有两个 DataFrame,比如:
df1 = pd.DataFrame([["tom", 1, 2, 3], ["bob", 3, 4, 5], ["ali", 6, 7, 8]], columns=["name", "A", "B", "C"])
df1
Out[44]:
name A B C
0 tom 1 2 3
1 bob 3 4 5
2 ali 6 7 8
df2 = pd.DataFrame([["rob", 1, 2, 3], ["ali", 6, 7, 8]], columns=["name", "A", "B", "D"])
df2
Out[46]:
name A B D
0 rob 1 2 3
1 ali 6 7 8
如何对具有相同“名称”和相同列的值执行求和运算,并获得如下结果 DataFrame:
name A B C D
0 tom 1 2 3 NaN # <- tom and bob don't shows up in df2, so the sum is identical
1 bob 3 4 5 NaN # to their values in df1
2 rob 1 2 NaN 3 # <- rob only shows up on df2, so the sum equal to its df2 values
3 ali 12 14 8 8 # <- ali's A and B are sum up, and C and D are identical to their
# corresponding value in df1 and df2
请注意,我不知道两个 DataFrame 的“名称”列中会显示什么名称。
而且,因为我有两个以上这样的 DataFrame 需要总结,如果可能的话,我怎样才能在一次操作中将所有这些 DataFrame 做到这一点,而不是一一总结?非常感谢。
【问题讨论】: