Logical comparisons are used everywhere.

The Pandas library gives you a lot of different ways that you can compare a DataFrame or Series to other Pandas objects, lists, scalar values, and more. The traditional comparison operators (<, >, <=, >=, ==, !=) can be used to compare a DataFrame to another set of values.

However, you can also use wrappers for more flexibility in your logical comparison operations. These wrappers allow you to specify the axis for comparison, so you can choose t to perform the comparison at the row or column level. Also, if you are working with a MultiIndex, you may specify which index you want to work with.

In this piece, we’ll first take a quick look at logical comparisons with the standard operators. After that, we’ll go through five different examples of how you can use these logical comparison wrappers to process and better understand your data.

The data used in this piece is sourced from Yahoo Finance. We’ll be using a subset of Tesla stock price data. Run the code below if you want to follow along. (And if you’re curious as to the function I used to get the data scroll to the very bottom and click on the first link.)

import pandas as pd

## fixed data so sample data will stay the same
df = pd.read_html("https://finance.yahoo.com/quote/TSLA/history?period1=1277942400&period2=1594857600&interval=1d&filter=history&frequency=1d")[0]
df = df.head(10) ## only work with the first 10 points

Image for post

Tesla stock data from Yahoo Finance

Logical Comparisons With Pandas

The wrappers available for use are:

  • eq (equivalent to ==) — equals to
  • ne (equivalent to !=) — not equals to
  • le (equivalent to <=) — less than or equals to
  • lt (equivalent to <) — less than
  • ge (equivalent to >=) — greater than or equals to
  • gt (equivalent to >) — greater than

#python #programming #pandas #data-science #technology

Using Logical Comparisons With Pandas DataFrames
2.80 GEEK