How to find a record which is not in a list in PySpark Azure Databricks?

Are you looking to find how to find records which is not in a list of a PySpark Dataframe using Azure Databricks cloud or maybe you are looking for a solution, to exclude records which is in a list of a Dataframe in PySpark using Azure Databricks? If you are looking for any of these problem solutions, then you have landed on the correct page. I will also show you how to perform the above action using different methods in Azure Databricks. I will explain it with a practical example. So don’t waste time let’s start with a step-by-step guide to understanding how to find records which is not in a defined list in PySpark Azure Databricks.

In this blog, I will teach you the following with practical examples:

  • PySpark isin()
  • PySpark NOT IN operator
  • PySpark SQL NOT IN operator

The PySpark isin() method is used to check whether values in a defind list is present or not and return a boolean value.

Syntax: column().isin()

What is the syntax of the isin() function in PySpark Azure Databricks?

The syntax is as follows:

column.isin(array)
Parameter NameRequiredDescription
array(List, Dict)YesIt represents the predefined values which have to be compared with the column.
Table 1: isin() Method in PySpark Databricks Parameter list with Details

Apache Spark Official documentation link: isin()

Create a simple DataFrame

Gentle reminder:

In Databricks,

  • sparkSession made available as spark
  • sparkContext made available as sc

In case, you want to create it manually, use the below code.

from pyspark.sql.session import SparkSession

spark = SparkSession.builder 
    .master("local[*]") 
    .appName("azurelib.com") 
    .getOrCreate()

sc = spark.sparkContext

a) Create manual PySpark DataFrame

data = [
    (1,"Em","VN"),
    (2,"Emalia","DE"),
    (3,"Odette",None),
    (4,"Mandy","DE"),
    (4,"Mandy","DE")
]

df = spark.createDataFrame(data, schema=["id","name","country"])
df.printSchema()
df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- country: string (nullable = true)

+---+------+-------+
|id |name  |country|
+---+------+-------+
|1  |Em    |VN     |
|2  |Emalia|DE     |
|3  |Odette|null   |
|4  |Mandy |DE     |
|4  |Mandy |DE     |
+---+------+-------+
"""

b) Creating a DataFrame by reading files

Download and use the below source file.

# replace the file_paths with the source file location which you have downloaded.

df_2 = spark.read.format("csv").option("header", True).load(file_path)
df_2.printSchema()

"""
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- country: string (nullable = true)
"""

Note: Here, I will be using the manually created DataFrame.

How to get records that are not in a list of PySpark DataFrame using isin() function?

In this section, let’s see how to get records that are not in a list of PySpark DataFrame using the isin() function with multiple methods and examples.

Example:

In the below example, we are trying to get the country records that are not in “VN”.

from pyspark.sql.functions import col

# Method 1:
df.filter(~col("country").isin(["VN"])).show()

# Method 2:
df.filter(col("country").isin(["VN"]) == False).show()

# The above two codes generates the following output

"""
Output:

+---+------+-------+
| id|  name|country|
+---+------+-------+
|  2|Emalia|     DE|
|  4| Mandy|     DE|
|  4| Mandy|     DE|
+---+------+-------+

"""

Note: The ‘~’ operator helps in finding the records that are specified in a defined list and neglects the null/None value too. This operator acts as NOT operator.

How to get records that are not in a list of PySpark DataFrame using NOT IN operator?

In this section, let’s see how to get records that are not in a list of PySpark DataFrame using NOT IN operator with an example.

Example:

In the below example, we are trying to get the country records that are not in “DE”.

df.filter("country NOT IN ('DE')").show()

"""
Output:

+---+----+-------+
| id|name|country|
+---+----+-------+
|  1|  Em|     VN|
+---+----+-------+

"""

How to get records that are not in a list of PySpark DataFrame using SQL expression?

In this section, let’s see how to get records that are not in a list of PySpark DataFrame using SQL expression with an example. In order to perform a raw SQL expression, we have to convert our DataFrame into SQL view.

Example:

df.createOrReplaceTempView("people")

spark.sql("""
SELECT * FROM people
WHERE country NOT IN ('DE')
""").show()

"""
Output:

+---+----+-------+
| id|name|country|
+---+----+-------+
|  1|  Em|     VN|
+---+----+-------+

"""

I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.

When should you use NOT isin() or NOT IN operator in PySpark Azure Databricks?

These could be the possible reasons:

  1. To find records not mentioned in a pre-defined list
  2. To filter out records, not in a list

Real World Use Case Scenarios for using NOT isin() or NOT IN operator in PySpark Azure Databricks?

  • Assume that you have a people dataset with id, name, and country. You want to fetch the people, not from China. The above-explained method will be helpful in fetching or removing those records from the DataFrame.

What are the alternatives for using NOT isin() or NOT IN operator in PySpark Azure Databricks?

There are multiple alternatives for creating PySpark columns, which are as follows:

  • isin()
  • NOT IN operator
  • SQL NOT IN operator

These are some of the alternative methods for using NOT isin operator and explained each and every method in detail above.

Final Thoughts

In this article, we have learned about finding records that are not a specified list in PySpark Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.

Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.

Arud Seka Berne S

As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.