python pandas:比较两列的相等性并产生第三个数据帧

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52777668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:04:43  来源:igfitidea点击:

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

pythonpandasdataframecomparisonconcat

提问by ravi

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

回答by jezrael

Use concatwith numpy.where:

使用concatnumpy.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