pandas to PySpark Cheatsheet

A side-by-side pandas to PySpark translation table: selects, filters, joins, group-bys, windows and dates, plus the mental-model shifts that trip people up.

PySparkPySpark 3.xpandasDataFrame APIUpdated

Four differences that explain everything else

pandasPySparkConsequence
Eager — every statement executes now.Lazy — transformations build a plan; only actions execute it.Errors surface late; repeated actions re-run the whole lineage unless you cache().
Has an index; row order is stable.No index; row order is undefined without orderBy.loc/iloc have no equivalent. Never rely on the order rows come back in.
Mutable — assign into a column in place.Immutable — every operation returns a new DataFrame.Use withColumn / select and reassign, or chain.
One machine, one memory space.Partitions spread across executors.Anything that reorders data by key is a shuffle, and shuffles dominate runtime.
Actions vs transformations
# Transformations (lazy, free until something asks for a result):
select  filter  withColumn  join  groupBy  orderBy  repartition  union  distinct

# Actions (each one launches a job):
show()  count()  collect()  take(n)  first()  toPandas()  write...()  foreach()

df.explain("formatted")   # read the plan without executing it
df.cache()                # materialise on first action, reuse afterwards
df.unpersist()            # give the memory back — cached data is not free

Reading and writing

TaskpandasPySpark
Read CSVpd.read_csv("f.csv")spark.read.option("header", True).schema(schema).csv("f.csv")
Read Parquetpd.read_parquet(path)spark.read.parquet(path)
Read JSON linespd.read_json(path, lines=True)spark.read.json(path)
Read a tablepd.read_sql("SELECT ...", conn)spark.table("db.orders") or spark.sql("SELECT ...")
Write Parquetdf.to_parquet(path)df.write.mode("overwrite").parquet(path)
Write partitionedmanual loopdf.write.partitionBy("dt").mode("overwrite").parquet(path)
Write one filedf.to_csv(path, index=False)df.coalesce(1).write.option("header", True).csv(path) — writes a directory, not a file
Save modesoverwrite by defaultmode(): "overwrite", "append", "ignore", "error" (default)

inferSchema=True reads the whole file once just to work out the types, then reads it again for the data. Pass an explicit StructType for anything running on a schedule — it halves the read and stops a stray value silently retyping a column between runs.

Inspecting, selecting, filtering

TaskpandasPySpark
Preview rowsdf.head(5)df.show(5, truncate=False) or df.limit(5).collect()
Schema / dtypesdf.info() / df.dtypesdf.printSchema() / df.dtypes
Row countlen(df) or df.shape[0]df.count() — a full job, not an attribute
Shapedf.shape(df.count(), len(df.columns))
Summary statsdf.describe()df.describe().show() or df.summary("count","min","25%","max").show()
Column listdf.columnsdf.columns
Select columnsdf[["a", "b"]]df.select("a", "b")
Select with expressiondf.assign(c=df.a * 2)[["c"]]df.selectExpr("a * 2 AS c")
Filterdf[df.a > 5]df.filter(F.col("a") > 5) or df.where("a > 5")
Multiple conditionsdf[(df.a > 5) & (df.b == "x")]df.filter((F.col("a") > 5) & (F.col("b") == "x")) — parentheses are mandatory in both
isindf[df.a.isin([1, 2])]df.filter(F.col("a").isin(1, 2))
betweendf[df.a.between(1, 5)]df.filter(F.col("a").between(1, 5))
Null testdf[df.a.isna()]df.filter(F.col("a").isNull())
Negationdf[~df.a.isna()]df.filter(F.col("a").isNotNull()) or ~F.col("a").isNull()
Distinct valuesdf.a.unique()df.select("a").distinct()
Value countsdf.a.value_counts()df.groupBy("a").count().orderBy(F.desc("count"))
Sampledf.sample(frac=0.1, random_state=42)df.sample(fraction=0.1, seed=42)

Creating and reshaping columns

TaskpandasPySpark
Add columndf["c"] = df.a + df.bdf = df.withColumn("c", F.col("a") + F.col("b"))
Add several at oncedf.assign(c=..., d=...)df.withColumns({"c": ..., "d": ...}) (Spark 3.3+) or one select
Renamedf.rename(columns={"a": "b"})df.withColumnRenamed("a", "b")
Dropdf.drop(columns=["a"])df.drop("a")
Castdf.a.astype("int64")df.withColumn("a", F.col("a").cast("bigint"))
Constant columndf["src"] = "web"df.withColumn("src", F.lit("web"))
Conditionalnp.where(df.a > 0, "pos", "neg")F.when(F.col("a") > 0, "pos").otherwise("neg")
Chained conditionsnp.select([...], [...])F.when(c1, v1).when(c2, v2).otherwise(v3)
Fill nullsdf.fillna({"a": 0})df.na.fill({"a": 0})
Drop null rowsdf.dropna(subset=["a"])df.na.drop(subset=["a"])
Replace valuesdf.replace({"a": {"x": "y"}})df.na.replace({"x": "y"}, subset=["a"])
Deduplicatedf.drop_duplicates(subset=["a"])df.dropDuplicates(["a"])
Sortdf.sort_values("a", ascending=False)df.orderBy(F.col("a").desc())
Sort with nulls lastdf.sort_values("a", na_position="last")df.orderBy(F.col("a").asc_nulls_last())
Reorder columnsdf[["b", "a"]]df.select("b", "a")

Calling withColumn in a Python loop builds a deeply nested plan and can make query analysis take minutes before a single row is read. Build a list of expressions and apply one select(*exprs), or use withColumns({...}).

Group by, join, reshape

TaskpandasPySpark
Group and aggregatedf.groupby("k").agg(total=("amt", "sum"))df.groupBy("k").agg(F.sum("amt").alias("total"))
Several aggregatesagg(total=("amt","sum"), n=("amt","count"))agg(F.sum("amt").alias("total"), F.count("*").alias("n"))
Count distinctdf.groupby("k").a.nunique()df.groupBy("k").agg(F.countDistinct("a"))
Approximate distinct—F.approx_count_distinct("a", 0.02) — far cheaper at scale
Collect into a listdf.groupby("k").a.apply(list)df.groupBy("k").agg(F.collect_list("a"))
Inner / left joinpd.merge(a, b, on="k", how="left")a.join(b, on="k", how="left")
Join on different namespd.merge(a, b, left_on="x", right_on="y")a.join(b, a.x == b.y, "inner")
Anti joina[~a.k.isin(b.k)]a.join(b, on="k", how="left_anti")
Semi joina[a.k.isin(b.k)]a.join(b, on="k", how="left_semi")
Concat rowspd.concat([a, b])a.unionByName(b, allowMissingColumns=True) — plain union() matches by position
Pivotdf.pivot_table(index="k", columns="c", values="v", aggfunc="sum")df.groupBy("k").pivot("c").agg(F.sum("v"))
Unpivot / meltpd.melt(df, id_vars=["k"])df.unpivot("k", ["a","b"], "name", "value") (Spark 3.4+) or a stack() expression
Explode a list columndf.explode("items")df.withColumn("item", F.explode("items"))

Passing on="k" as a string keeps one join column; passing a condition (a.k == b.k) keeps both and you get two columns with the same name — the source of most "Reference k is ambiguous" errors.

Windows, strings and dates

TaskpandasPySpark
Cumulative sum per groupdf.groupby("k").v.cumsum()F.sum("v").over(Window.partitionBy("k").orderBy("d").rowsBetween(Window.unboundedPreceding, 0))
Rank within groupdf.groupby("k").v.rank(method="first")F.row_number().over(Window.partitionBy("k").orderBy("v"))
Previous rowdf.groupby("k").v.shift(1)F.lag("v", 1).over(Window.partitionBy("k").orderBy("d"))
Rolling meandf.v.rolling(3).mean()F.avg("v").over(Window.orderBy("d").rowsBetween(-2, 0))
Group total on each rowdf.groupby("k").v.transform("sum")F.sum("v").over(Window.partitionBy("k"))
Uppercasedf.s.str.upper()F.upper("s")
Containsdf.s.str.contains("abc")F.col("s").contains("abc") or F.col("s").rlike("abc")
Regex replacedf.s.str.replace(r"\d+", "", regex=True)F.regexp_replace("s", r"\d+", "")
Splitdf.s.str.split(",")F.split("s", ",")
Concatenatedf.a + "-" + df.bF.concat_ws("-", "a", "b")
Parse a datepd.to_datetime(df.d)F.to_date("d", "yyyy-MM-dd") / F.to_timestamp("d")
Date partdf.d.dt.yearF.year("d")
Format a datedf.d.dt.strftime("%Y-%m")F.date_format("d", "yyyy-MM")
Date arithmeticdf.d + pd.Timedelta(days=7)F.date_add("d", 7)
Difference in days(a - b).dt.daysF.datediff("a", "b")
Current datepd.Timestamp.today()F.current_date() / F.current_timestamp()

Date format strings are Java patterns, not strftime: yyyy-MM-dd HH:mm:ss. Lowercase mm is minutes and uppercase DD is day-of-year, so a wrong case silently produces wrong dates rather than an error.

Escape hatches — apply, UDFs and going back to pandas

In order of preference
# 1. Built-in expression — runs in the JVM, fully optimised. Always try first.
df = df.withColumn("clean", F.trim(F.lower(F.col("name"))))

# 2. pandas UDF — vectorised, Arrow-serialised, one call per batch.
from pyspark.sql.functions import pandas_udf
import pandas as pd

@pandas_udf("double")
def norm(s: pd.Series) -> pd.Series:
    return (s - s.mean()) / s.std()

df = df.withColumn("z", norm("amount"))

# 3. mapInPandas — arbitrary pandas code over batches of rows.
def clean(batches):
    for pdf in batches:
        yield pdf.assign(name=pdf["name"].str.strip())

df = df.mapInPandas(clean, schema=df.schema)

# 4. Plain Python UDF — one Python call per ROW, with serialisation both
#    ways and no optimiser visibility. Correct, and the slowest option.
@F.udf("string")
def slow(x):
    return x.strip()

# 5. pandas API on Spark — pandas syntax, Spark execution.
import pyspark.pandas as ps
psdf = df.pandas_api()          # or ps.read_parquet(path)
psdf["z"] = psdf["amount"] * 2
sdf = psdf.to_spark()
TaskpandasPySpark
Row-wise applydf.apply(f, axis=1)No direct equivalent — express it with columns, or use mapInPandas
Iterate rowsfor _, r in df.iterrows()df.collect() (small results only) or df.toLocalIterator()
Convert to pandas—df.toPandas() — pulls everything into driver memory
Convert from pandas—spark.createDataFrame(pdf)
Speed up both conversions—spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")

toPandas() and collect() move the entire result into the driver JVM and then into Python. On a 50 GB DataFrame that is a driver OOM, not a slow cell. Aggregate or limit() first, always.

Gotchas when you port working pandas code

SymptomCause
Results differ between runsNo orderBy. Spark makes no ordering promise, and partition scheduling varies.
Notebook cell is instant, next cell takes 20 minutesLaziness — the earlier cell only built a plan. The action pays for all of it.
The same query gets slower each loop iterationThe lineage is re-executed every action. cache() the reused DataFrame, or write it out and read it back.
NULL comparisons behave oddlySQL three-valued logic: NULL = NULL is NULL, not True. Use isNull() or the null-safe eqNullSafe().
NaN and NULL behave differentlySpark keeps them distinct: F.isnan() is not isNull(). pandas conflates the two.
Column not found, but it is right thereSpark resolves column names case-insensitively by default, and a trailing space or a leading BOM in a CSV header is invisible in show().
Reference is ambiguousBoth sides of a join contributed a column with that name. Alias the DataFrames or join on a name list.
Overwrite deleted more than expectedmode("overwrite") replaces the whole output path. Set spark.sql.sources.partitionOverwriteMode=dynamic to replace only the partitions being written.
Thousands of tiny output filesOne output file per partition. coalesce() before writing, or repartition by the partition column.
A UDF that worked locally fails on the clusterThe closure captured an object that cannot be pickled, or a library that is not installed on the executors.

pandas to PySpark Cheatsheet · https://ctarunsai.github.io/cheatsheets/pandas-to-pyspark/ · updated 28 Aug 2026 · Tarun Chitta

About this cheatsheet

The pandas and PySpark DataFrame APIs look similar enough to be dangerous. Most of the vocabulary translates one-for-one, and then four differences bite: PySpark is lazy, it has no index, DataFrames are immutable, and your data is spread across partitions on other machines. Every surprising result traces back to one of those four.

Lazy means nothing runs until an action — show, count, collect, write — asks for a result. Chaining twenty transformations costs nothing; the plan is optimised as a whole when you finally trigger it. It also means an error in the middle of your notebook can surface twenty cells later, and that calling df.count() inside a loop re-executes the entire lineage every iteration.

No index means loc, iloc, reset_index and anything that depends on row position has no equivalent. Row order is not preserved unless you orderBy, and monotonically_increasing_id() is unique but not sequential. Immutability means df["c"] = ... does not exist — every operation returns a new DataFrame, so you reassign or you chain.

The tables below are direct translations, assuming from pyspark.sql import functions as F and from pyspark.sql.window import Window. The last two sections cover the things that have no clean translation at all, and the mistakes that make a working translation slow.