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

三世轮回 提交于 2020-05-12 05:04:12

问题


how to print the result in the separate dataframe after comparing it with two columns in different dataframes.

consider two dataframes:

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

now the result should be in a different dataframe.

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

回答1:


Use concat with 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


来源:https://stackoverflow.com/questions/52777668/python-pandas-compare-two-columns-for-equality-and-result-in-third-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!