Skip to main content
 首页 » 编程设计

python之比较 Pandas 中两个不同的行和列数据框

2025年02月15日10sxdcgaq8080

我这里有两个数据框:

A:d e,d c,a c,

B:a c,d c,

有不同数量的行。(没有相等的行)。如果 A 中的一行与 B 中的一行匹配。我们用 A 的第一列替换 A 的第二列。所以结果应该是:

C:d e,d d,a a,

请您参考如下方法:

您可以对所有列的两个数据帧进行左连接,指定indicator=True,以便结果保留_merge列这表明 A 中的行是否与 B 中的行匹配,并相应地更新第二列:

A_ = A.merge(B.drop_duplicates(), indicator=True, how="left") 
 
# if the row comes from left only then don't make change, otherwise update the second column  
# with first column value 
A_[1] = A_[1].where(A_._merge == "left_only", A_[0])    
A_.drop('_merge', 1) 
 
#   0   1 
#0  d   e 
#1  d   d 
#2  a   a 

A = pd.DataFrame([['d','e'],['d','c'],['a','c']]) 
B = pd.DataFrame([['a','c'],['d','c']])