This is a practical PySpark functions cheat sheet covering the most frequently used DataFrame, SQL, and RDD operations, with syntax examples for Spark 3.x. The core functions you will use daily include select(), filter(), groupBy(), agg(), join(), and withColumn(), plus window functions and string/date utilities.
Why You Need a Cheat Sheet for PySpark
PySpark is the Python API for Apache Spark, a distributed computing engine designed to process large datasets across clusters. Unlike pandas, which loads data into a single machine’s memory, PySpark uses a lazy evaluation model: transformations are recorded as a lineage graph and only executed when an action (like collect() or count()) is called. This means you must think in terms of DataFrames and SQL-like operations rather than row-wise loops. A cheat sheet helps you avoid the most common mistake—using pandas-style code on a Spark DataFrame—and keeps your transformations efficient.
Spark 3.x introduced the Pandas API on Spark (formerly Koalas) for users who prefer pandas syntax, but the core PySpark DataFrame API remains the standard for production jobs. Knowing the exact function names and argument order saves debugging time, especially when you are working with complex ETL pipelines or feature engineering for machine learning.
Core DataFrame Transformations
These are the bread-and-butter operations you will use in almost every PySpark script. Assume you have a DataFrame df with columns id, name, age, and salary.
df.select("name", "age")– picks specific columns.df.selectExpr("age * 2 as double_age")– runs SQL expressions on columns.df.filter(df.age > 30)ordf.where("age > 30")– filters rows.df.drop("salary")– removes a column.df.withColumn("age_plus_one", df.age + 1)– adds or replaces a column.df.withColumnRenamed("name", "full_name")– renames a column.df.distinct()– removes duplicate rows.df.dropDuplicates(["id"])– removes rows with duplicate values in specific columns.
For example, to filter and add a column in one chain:
df.filter(df.age > 25) \
.withColumn("seniority", when(df.age > 50, "senior").otherwise("junior")) \
.select("name", "seniority")
Note that when() and otherwise() are from pyspark.sql.functions and are the equivalent of a CASE statement in SQL.
Aggregations and Grouping
Grouping and aggregating is where PySpark shines. Use groupBy() followed by agg() with one or more aggregate functions.
df.groupBy("department").count()– counts rows per group.df.groupBy("department").agg(sum("salary"), avg("age"))– multiple aggregates.df.groupBy("department").agg({"salary": "sum", "age": "avg"})– dictionary form.df.rollup("department", "sub_dept").sum("salary")– subtotals and grand total.df.cube("department", "sub_dept").avg("salary")– all combinations of grouping columns.
Common aggregate functions from pyspark.sql.functions: sum(), avg(), min(), max(), count(), countDistinct(), collect_list(), and collect_set(). For example, to get the average salary per department:
from pyspark.sql.functions import avg
df.groupBy("department").agg(avg("salary").alias("avg_salary")).show()
Remember that show() is an action that prints the result to the console; without it, nothing executes.
Joining DataFrames
Joins in PySpark are similar to SQL, but you must specify the join type and the condition. The default is inner join.
df1.join(df2, df1.id == df2.id)– inner join.df1.join(df2, df1.id == df2.id, "left")– left outer join.df1.join(df2, df1.id == df2.id, "right")– right outer join.df1.join(df2, df1.id == df2.id, "full")– full outer join.df1.join(df2, df1.id == df2.id, "semi")– keeps only rows from left that have matches.df1.join(df2, df1.id == df2.id, "anti")– keeps only rows from left with no matches.
If the join columns have the same name, you can use df1.join(df2, "id") and Spark will automatically use that column. For complex conditions, pass a string expression: df1.join(df2, "df1.id == df2.id AND df1.date == df2.date"). Be careful with column name collisions; use alias() to rename DataFrames before joining if needed.
Window Functions for Ranking and Running Totals
Window functions let you compute values across a set of rows related to the current row, like row numbers or cumulative sums. You need to define a window specification using Window.partitionBy() and orderBy().
from pyspark.sql.window import Window
from pyspark.sql.functions import row_number, rank, sum
window_spec = Window.partitionBy("department").orderBy(df.salary.desc())
df.withColumn("row_num", row_number().over(window_spec)) \
.withColumn("cum_salary", sum("salary").over(window_spec))
Key window functions: row_number(), rank(), dense_rank(), lag(), lead(), ntile(), and cume_dist(). The difference between rank() and dense_rank() is that rank() leaves gaps in the ranking sequence when there are ties, while dense_rank() does not. For example, with salaries (100, 100, 90), rank() gives 1,1,3; dense_rank() gives 1,1,2.
String, Date, and Null Handling Functions
PySpark provides a rich set of built-in functions for cleaning and transforming data. Import them from pyspark.sql.functions.
- String:
upper(),lower(),trim(),split(),substring(),concat(),concat_ws(),regexp_replace(),length(). - Date:
current_date(),date_add(),datediff(),year(),month(),dayofmonth(),to_date(),date_format(). - Null:
isnull(),isnotnull(),coalesce(),nanvl(),dropna()(DataFrame method),fillna()(DataFrame method).
Example: convert a string column to date and extract the year.
from pyspark.sql.functions import to_date, year
df.withColumn("date", to_date("date_str", "yyyy-MM-dd")) \
.withColumn("year", year("date"))
For null handling, df.dropna() removes rows with any nulls, df.dropna(subset=["age"]) only removes rows where age is null, and df.fillna(0) replaces nulls with 0. Use coalesce(col1, col2) to return the first non-null value among columns.
Working with Complex Types (Arrays and Maps)
PySpark supports array and map columns, which are common when dealing with JSON or nested data. Key functions include:
array()– creates an array from columns.array_contains()– checks if array contains a value.explode()– splits array into multiple rows.explode_outer()– same but keeps rows with null/empty arrays.size()– returns array length.getItem()– extracts element by index or key.map_keys(),map_values()– extract keys/values from a map.
Example: explode an array column to flatten the data.
from pyspark.sql.functions import explode
df.withColumn("item", explode("items"))
This turns each element of the items array into its own row, duplicating other columns as needed.
Reading and Writing Data
PySpark can read from and write to many formats: CSV, JSON, Parquet, ORC, Avro, JDBC, and more. The syntax is consistent: spark.read.format("csv").option(...).load(path) and df.write.format("parquet").save(path).
- CSV:
spark.read.csv("file.csv", header=True, inferSchema=True)– note thatinferSchematriggers an extra pass but is often worth it. - Parquet:
spark.read.parquet("file.parquet")– preferred for performance and schema preservation. - JSON:
spark.read.json("file.json")– handles nested structures automatically. - Write with partitioning:
df.write.partitionBy("year").parquet("output")– creates subdirectories by partition column.
For writing, you can specify mode("overwrite") or mode("append") to control behavior if the output path exists. Always use .save() or format-specific methods like .csv().
Performance Tips and Common Pitfalls
PySpark is powerful but easy to misuse. Here are the most important performance considerations:
- Avoid
collect()on large DataFrames – it pulls all data to the driver and can crash it. Usetake(n)orshow(n)for inspection. - Use
broadcast()for small lookup tables –df.join(broadcast(small_df), "key")avoids a full shuffle. - Minimize shuffles – operations like
groupBy(),join(), anddistinct()cause data movement. Filter early to reduce data size. - Cache intermediate results –
df.cache()ordf.persist()if you reuse the same DataFrame multiple times. - Use
select()instead ofwithColumn()for many columns –withColumn()creates a new DataFrame each time, which can be slower.
A common misconception is that PySpark is a drop-in replacement for pandas. It is not; pandas is for in-memory single-machine data, while PySpark is for distributed data. If your data fits in memory on one machine, pandas will be faster and simpler. Use PySpark when you have gigabytes to terabytes of data or need distributed processing.
Frequently Asked Questions
What is the difference between transform() and withColumn()?
withColumn() adds or replaces a single column and returns a new DataFrame. transform() is a DataFrame method that applies a function to the entire DataFrame, often used in pipelines to chain multiple transformations. For example, df.transform(remove_nulls).transform(add_id) applies each function in sequence.
How do I convert a PySpark DataFrame to a pandas DataFrame?
Use df.toPandas(). This collects all data to the driver and creates a pandas DataFrame. It is only safe for small DataFrames; doing this on a large dataset can cause out-of-memory errors. Alternatively, use df.limit(1000).toPandas() to sample.
Why is my groupBy().count() returning nulls for some groups?
This usually happens when the grouping column contains null values. In Spark, nulls are treated as a separate group. If you want to exclude nulls, filter them out before grouping: df.filter(df.col.isNotNull()).groupBy("col").count().
Can I use SQL queries on a DataFrame?
Yes. Register the DataFrame as a temporary view: df.createOrReplaceTempView("my_table"), then run spark.sql("SELECT * FROM my_table WHERE age > 30"). This is useful for complex queries that are easier to write in SQL.
What does persist() do and when should I use it?
persist() stores the DataFrame in memory and/or disk so that subsequent actions don’t recompute it from scratch. Use it when you will call multiple actions (like count() and show()) on the same DataFrame, or when a transformation is expensive. You can specify storage level like MEMORY_ONLY or MEMORY_AND_DISK.
How do I handle nested JSON in PySpark?
Use from_json() with a schema to parse a string column into a struct, then access nested fields with dot notation (e.g., df.select("nested.field")). For arrays, use explode() to flatten. Example: df.withColumn("parsed", from_json("json_str", schema)).select("parsed.name").
Related
- Hitachi WH18DBL Brushless Impact Driver Review
- COUNTIF Multiple Criteria in Google Sheets (3 Ways)
- Random Number Generator: How to Get One Instantly
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel COUNTIF Not a Number? Count Text, Blanks, and ErrorsCOUNTIF can count cells that match a criterion, but it does not have a built-in criterion meaning “is…
- Excel: How to Hide Columns to the Right of Your DataTo hide every column to the right of your data in Excel for Microsoft 365 on Windows, select…
- Excel Filter Shortcut Key: Turn Filtering On or OffTo apply a filter in Excel for Microsoft 365 on Windows, click a cell in your data range…
- Excel Filter Multiple Criteria in One Column: How It WorksTo filter one Excel column for several allowed values, select the column’s filter arrow and check each value…
- Concatenate First Letter and Last Name in ExcelIf first names are in A2 and last names are in B2, enter =LEFT(TRIM(A2),1)&" "&TRIM(B2) to combine the…
- How to Copy Text Only in Excel Without Copying FormulasTo copy a formula’s result without copying the formula in Excel, select the cell or range, press Ctrl+C,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.