In Pandas, can we compare the values of two columns in the same dataframe?


#1

Question

In Pandas, can we compare the values of two columns in the same dataframe?

Answer

Yes, you can compare values of different columns of a dataframe within the logical statement.

Say for example, you had data that stored the buy price and sell price of stocks in two columns. If you wanted to select rows of the data for which the buy price was less than the sell price, you could compare their values in the logical statement.

Example

# This logical statement is comparing 
# the values of column `buy_price`
# and column `sell_price`
gains = df[df.buy_price < df.sell_price]