Skip to main content
 首页 » 编程设计

python Pandas : compare two columns for equality and result in third dataframe

2025年05月04日11Free-Thinker

如何在将结果与不同数据框中的两列进行比较后在单独的数据框中打印结果。

考虑两个数据框:

df1 = pd.DataFrame({'col1':['audi','cars']})   
df2 = pd.DataFrame({'col2':['audi','bike']}) 
 
print (df1) 
 
    col1 
0  audi 
1  cars  
 
print (df2) 
 
     col2 
0   audi 
1   bike 

现在结果应该在不同的数据框中。

      col1  col2  result 
0     audi  audi   no change 
1     cars  bike   changed 

请您参考如下方法:

使用concat与 numpy.where :

df = pd.concat([df1, df2], axis=1) 
df['result'] = np.where(df['col1'] == df['col2'], 'no change', 'changed') 
print (df) 
   col1  col2     result 
0  audi  audi  no change 
1  cars  bike    changed