PySpark Column Class | Operators & Functions

Spread the love

pyspark.sql.Column class provides several functions to work with DataFrame to manipulate the Column values, evaluate the boolean expression to filter rows, retrieve a value or part of a value from a DataFrame column, and to work with list, map & struct columns.

In this article, I will cover how to create Column object, access them to perform operations, and finally most used PySpark Column Functions with Examples.

Related Article: PySpark Row Class with Examples

Key Points:

  • PySpark Column class represents a single Column in a DataFrame.
  • It provides functions that are most used to manipulate DataFrame Columns & Rows.
  • Some of these Column functions evaluate a Boolean expression that can be used with filter() transformation to filter the DataFrame Rows.
  • Provides functions to get a value from a list column by index, map value by key & index, and finally struct nested column.
  • PySpark also provides additional functions pyspark.sql.functions that take Column object and return a Column type.

Note: Most of the pyspark.sql.functions return Column type hence it is very important to know the operation you can perform with Column type.

1. Create Column Class Object

One of the simplest ways to create a Column class object is by using PySpark lit() SQL function, this takes a literal value and returns a Column object.

from pyspark.sql.functions import lit
colObj = lit("")

You can also access the Column from DataFrame by multiple ways.

# |-- name.fname: string (nullable = true)
# |-- gender: long (nullable = true)

# Using DataFrame object (df)["gender"]).show()
#Accessing column name with dot (with backticks)["`name.fname`"]).show()

#Using SQL col() function
from pyspark.sql.functions import col"gender")).show()
#Accessing column name with dot (with backticks)"`name.fname`")).show()

Below example demonstrates accessing struct type columns. Here I have use PySpark Row class to create a struct type. Alternatively you can also create it by using PySpark StructType & StructField classes

#Create DataFrame with struct using Row class
from pyspark.sql import Row
# |-- name: string (nullable = true)
# |-- prop: struct (nullable = true)
# |    |-- hair: string (nullable = true)
# |    |-- eye: string (nullable = true)

#Access struct column[""]).show()"")).show()

#Access all columns from struct"prop.*")).show()

2. PySpark Column Operators

PySpark column also provides a way to do arithmetic operations on columns using operators.


#Arthmetic operations + df.col2).show() - df.col2).show() * df.col2).show() / df.col2).show() % df.col2).show() > df.col3).show() < df.col3).show() == df.col3).show()

3. PySpark Column Functions

Let’s see some of the most used Column Functions, on below table, I have grouped related functions together to make it easy, click on the link for examples.

Column FunctionFunction Description
alias(*alias, **kwargs)
name(*alias, **kwargs)
Provides alias to the column or expressions
name() returns same as alias().
Returns ascending order of the column.
asc_nulls_first() Returns null values first then non-null values.
asc_nulls_last() – Returns null values after non-null values.
Used to cast the data type to another type.
astype() returns same as cast().
between(lowerBound, upperBound)Checks if the columns values are between lower and upper bound. Returns boolean value.
Compute bitwise AND, OR & XOR of this expression with another expression respectively.
contains(other)Check if String contains in another string.
Returns descending order of the column.
desc_nulls_first() -null values appear before non-null values.
desc_nulls_last() – null values appear after non-null values.
String starts with. Returns boolean expression
String ends with. Returns boolean expression
eqNullSafe(other)Equality test that is safe for null values.
getField(name)Returns a field by name in a StructField and by key in Map.
getItem(key)Returns a values from Map/Key at the provided position.
isNotNull() – Returns True if the current expression is NOT null.
isNull() – Returns True if the current expression is null.
isin(*cols)A boolean expression that is evaluated to true if the value of this expression is contained by the evaluated values of the arguments.
Similar to SQL like expression.
Similar to SQL RLIKE expression (LIKE with Regex).
over(window)Used with window column
substr(startPos, length)Return a Column which is a substring of the column.
when(condition, value)
Similar to SQL CASE WHEN, Executes a list of conditions and returns one of multiple possible result expressions.
dropFields(*fieldNames)Used to drops fields in StructType by name.
withField(fieldName, col)An expression that adds/replaces a field in StructType by name.

4. PySpark Column Functions Examples

Let’s create a simple DataFrame to work with PySpark SQL Column examples. For most of the examples below, I will be referring DataFrame object name (df.) to get the column.

      ("Tom Cruise","XXX","400",''),
      ("Tom Brand",None,"400",'M')] 

4.1 alias() – Set’s name to Column

On below example df.fname refers to Column object and alias() is a function of the Column to give alternate name. Here, fname column has been changed to first_name & lname to last_name.

On second example I have use PySpark expr() function to concatenate columns and named column as fullName.

from pyspark.sql.functions import expr"first_name"), \

#Another example" fname ||','|| lname").alias("fullName") \

4.2 asc() & desc() – Sort the DataFrame columns by Ascending or Descending order.

#asc, desc to sort ascending and descending order repsectively.

4.3 cast() & astype() – Used to convert the data Type.


4.4 between() – Returns a Boolean expression when a column values in between lower and upper bound.


4.5 contains() – Checks if a DataFrame column value contains a a value specified in this function.


4.6 startswith() & endswith() – Checks if the value of the DataFrame Column starts and ends with a String respectively.

#startswith, endswith()

4.7 eqNullSafe() –

4.8 isNull & isNotNull() – Checks if the DataFrame column has NULL or non NULL values.

Refer to

#isNull & isNotNull

4.9 like() & rlike() – Similar to SQL LIKE expression

#like , rlike,df.lname, \

4.10 substr() – Returns a Column after getting sub string from the Column,2).alias("substr")).show()

4.11 when() & otherwise() – It is similar to SQL Case When, executes sequence of expressions until it matches the condition and returns a value when match.

#when & otherwise
from pyspark.sql.functions import when,df.lname,when(df.gender=="M","Male") \
              .when(df.gender=="F","Female") \
              .when(df.gender==None ,"") \
              .otherwise(df.gender).alias("new_gender") \

4.12 isin() – Check if value presents in a List.

li=["100","200"],df.lname, \
  .filter( \

4.13 getField() – To get the value by key from MapType column and by stuct child name from StructType column

Rest of the below functions operates on List, Map & Struct data structures hence to demonstrate these I will use another DataFrame with list, map and struct columns. For more explanation how to use Arrays refer to PySpark ArrayType Column on DataFrame Examples & for map refer to PySpark MapType Examples

#Create DataFrame with struct, array & map
from pyspark.sql.types import StructType,StructField,StringType,ArrayType,MapType
      (("Tom Cruise",""),["Python","Scala"],{'hair':'red','eye':'grey'}),
      (("Tom Brand",None),["Perl","Ruby"],{'hair':'black','eye':'blue'})]

schema = StructType([
        StructField('name', StructType([
            StructField('fname', StringType(), True),
            StructField('lname', StringType(), True)])),
        StructField('languages', ArrayType(StringType()),True),
        StructField('properties', MapType(StringType(),StringType()),True)

#Display's to console
 |-- name: struct (nullable = true)
 |    |-- fname: string (nullable = true)
 |    |-- lname: string (nullable = true)
 |-- languages: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- properties: map (nullable = true)
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)

getField Example

#getField from MapType"hair")).show()

#getField from Struct"fname")).show()

4.14 getItem() – To get the value by index from MapType or ArrayTupe & ny key for MapType column.

#getItem() used with ArrayType

#getItem() used with MapType"hair")).show()

4.15 dropFields –

# TO-DO, getting runtime error

4.16 withField() –

# TO-DO getting runtime error

4.17 over() – Used with Window Functions


Happy Learning !!

Related Article

Naveen (NNK) is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

You are currently viewing PySpark Column Class | Operators & Functions