close

How to compare two columns of the same dataframe?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to compare two columns of the same dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to compare two columns of the same dataframe?

  1. How to compare two columns of the same dataframe?

    Typically, if you find yourself trying to iterate explicitly as you were to set a column, there is an abstraction like apply or where which will be both faster and more concise.

  2. compare two columns of the same dataframe

    Typically, if you find yourself trying to iterate explicitly as you were to set a column, there is an abstraction like apply or where which will be both faster and more concise.

Method 1

You can more easily use np.where.

high_scores1['is_score_chased'] = np.where(high_scores1['runs1']>=high_scores1['runs2'], 
                                           'yes', 'no')

Typically, if you find yourself trying to iterate explicitly as you were to set a column, there is an abstraction like apply or where which will be both faster and more concise.

Method 2

This is a good case for using apply.

Here there is an example of using apply on two columns.

You can adapt it to your question with this:

def f(x):    
   return 'yes' if x['run1'] > x['run2'] else 'no'

df['is_score_chased'] = df.apply(f, axis=1)

However, I would suggest filling your column with booleans so you can make it more simple

def f(x):    
   return x['run1'] > x['run2']

And also using lambdas so you make it in one line

df['is_score_chased'] = df.apply(lambda x: x['run1'] > x['run2'], axis=1)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read