Python 熊猫:添加一列';如果索引存在,则将s值转换为另一个

Python 熊猫:添加一列';如果索引存在,则将s值转换为另一个,python,pandas,Python,Pandas,我有两个数据帧: A: B: 我想将索引存在于A中的B的值添加到A的列(在具有相应索引的行上),而不使用 在A中没有相应索引的B中的值被添加或删除在A和B中都不存在的索引: foo bar foo2 0 2 1 1 1 2 2 2 2 5 3 3 3 6 3 3 我觉得这应该是直截了当的,但是使用add和concat我得到的不是A的所有行,也不是A和B的并集通过使用add和fill_v

我有两个数据帧:

A:

B:

我想将索引存在于A中的B的值添加到A的列(在具有相应索引的行上),而不使用 在A中没有相应索引的B中的值被添加或删除在A和B中都不存在的索引:

   foo   bar   foo2  
0   2     1     1      
1   2     2     2
2   5     3     3
3   6     3     3

我觉得这应该是直截了当的,但是使用
add
concat
我得到的不是A的所有行,也不是A和B的并集

通过使用
add
fill_value=0
,最后还需要
dropna

A.add(B,fill_value=0).dropna().astype(int)
Out[434]: 
   bar  foo  foo2
0    1    2     1
1    2    2     2
2    3    5     3
3    3    4     3

简单、直接、高效-使用集合运算获得索引的交点,然后执行基于
loc
的算术-

i = A.index.intersection(B.index)
j = A.columns.intersection(B.columns)

A.loc[i, j] += B.loc[i, j]

你能行

A["foo"] = (A["foo"] + B["foo"]).fillna(A["foo"])

另一种选择可能是:

result_df = (A + B).fillna(A).dropna()
print(result_df)
结果:

   bar  foo  foo2
0  1.0  2.0   1.0
1  2.0  2.0   2.0
2  3.0  5.0   3.0
3  3.0  4.0   3.0
A["foo"] = (A["foo"] + B["foo"]).fillna(A["foo"])
result_df = (A + B).fillna(A).dropna()
print(result_df)
   bar  foo  foo2
0  1.0  2.0   1.0
1  2.0  2.0   2.0
2  3.0  5.0   3.0
3  3.0  4.0   3.0