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.
Four differences that explain everything else
| pandas | PySpark | Consequence |
|---|---|---|
| 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. |
# 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 freeReading and writing
| Task | pandas | PySpark |
|---|---|---|
| Read CSV | pd.read_csv("f.csv") | spark.read.option("header", True).schema(schema).csv("f.csv") |
| Read Parquet | pd.read_parquet(path) | spark.read.parquet(path) |
| Read JSON lines | pd.read_json(path, lines=True) | spark.read.json(path) |
| Read a table | pd.read_sql("SELECT ...", conn) | spark.table("db.orders") or spark.sql("SELECT ...") |
| Write Parquet | df.to_parquet(path) | df.write.mode("overwrite").parquet(path) |
| Write partitioned | manual loop | df.write.partitionBy("dt").mode("overwrite").parquet(path) |
| Write one file | df.to_csv(path, index=False) | df.coalesce(1).write.option("header", True).csv(path) — writes a directory, not a file |
| Save modes | overwrite by default | mode(): "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
| Task | pandas | PySpark |
|---|---|---|
| Preview rows | df.head(5) | df.show(5, truncate=False) or df.limit(5).collect() |
| Schema / dtypes | df.info() / df.dtypes | df.printSchema() / df.dtypes |
| Row count | len(df) or df.shape[0] | df.count() — a full job, not an attribute |
| Shape | df.shape | (df.count(), len(df.columns)) |
| Summary stats | df.describe() | df.describe().show() or df.summary("count","min","25%","max").show() |
| Column list | df.columns | df.columns |
| Select columns | df[["a", "b"]] | df.select("a", "b") |
| Select with expression | df.assign(c=df.a * 2)[["c"]] | df.selectExpr("a * 2 AS c") |
| Filter | df[df.a > 5] | df.filter(F.col("a") > 5) or df.where("a > 5") |
| Multiple conditions | df[(df.a > 5) & (df.b == "x")] | df.filter((F.col("a") > 5) & (F.col("b") == "x")) — parentheses are mandatory in both |
| isin | df[df.a.isin([1, 2])] | df.filter(F.col("a").isin(1, 2)) |
| between | df[df.a.between(1, 5)] | df.filter(F.col("a").between(1, 5)) |
| Null test | df[df.a.isna()] | df.filter(F.col("a").isNull()) |
| Negation | df[~df.a.isna()] | df.filter(F.col("a").isNotNull()) or ~F.col("a").isNull() |
| Distinct values | df.a.unique() | df.select("a").distinct() |
| Value counts | df.a.value_counts() | df.groupBy("a").count().orderBy(F.desc("count")) |
| Sample | df.sample(frac=0.1, random_state=42) | df.sample(fraction=0.1, seed=42) |
Creating and reshaping columns
| Task | pandas | PySpark |
|---|---|---|
| Add column | df["c"] = df.a + df.b | df = df.withColumn("c", F.col("a") + F.col("b")) |
| Add several at once | df.assign(c=..., d=...) | df.withColumns({"c": ..., "d": ...}) (Spark 3.3+) or one select |
| Rename | df.rename(columns={"a": "b"}) | df.withColumnRenamed("a", "b") |
| Drop | df.drop(columns=["a"]) | df.drop("a") |
| Cast | df.a.astype("int64") | df.withColumn("a", F.col("a").cast("bigint")) |
| Constant column | df["src"] = "web" | df.withColumn("src", F.lit("web")) |
| Conditional | np.where(df.a > 0, "pos", "neg") | F.when(F.col("a") > 0, "pos").otherwise("neg") |
| Chained conditions | np.select([...], [...]) | F.when(c1, v1).when(c2, v2).otherwise(v3) |
| Fill nulls | df.fillna({"a": 0}) | df.na.fill({"a": 0}) |
| Drop null rows | df.dropna(subset=["a"]) | df.na.drop(subset=["a"]) |
| Replace values | df.replace({"a": {"x": "y"}}) | df.na.replace({"x": "y"}, subset=["a"]) |
| Deduplicate | df.drop_duplicates(subset=["a"]) | df.dropDuplicates(["a"]) |
| Sort | df.sort_values("a", ascending=False) | df.orderBy(F.col("a").desc()) |
| Sort with nulls last | df.sort_values("a", na_position="last") | df.orderBy(F.col("a").asc_nulls_last()) |
| Reorder columns | df[["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
| Task | pandas | PySpark |
|---|---|---|
| Group and aggregate | df.groupby("k").agg(total=("amt", "sum")) | df.groupBy("k").agg(F.sum("amt").alias("total")) |
| Several aggregates | agg(total=("amt","sum"), n=("amt","count")) | agg(F.sum("amt").alias("total"), F.count("*").alias("n")) |
| Count distinct | df.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 list | df.groupby("k").a.apply(list) | df.groupBy("k").agg(F.collect_list("a")) |
| Inner / left join | pd.merge(a, b, on="k", how="left") | a.join(b, on="k", how="left") |
| Join on different names | pd.merge(a, b, left_on="x", right_on="y") | a.join(b, a.x == b.y, "inner") |
| Anti join | a[~a.k.isin(b.k)] | a.join(b, on="k", how="left_anti") |
| Semi join | a[a.k.isin(b.k)] | a.join(b, on="k", how="left_semi") |
| Concat rows | pd.concat([a, b]) | a.unionByName(b, allowMissingColumns=True) — plain union() matches by position |
| Pivot | df.pivot_table(index="k", columns="c", values="v", aggfunc="sum") | df.groupBy("k").pivot("c").agg(F.sum("v")) |
| Unpivot / melt | pd.melt(df, id_vars=["k"]) | df.unpivot("k", ["a","b"], "name", "value") (Spark 3.4+) or a stack() expression |
| Explode a list column | df.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
| Task | pandas | PySpark |
|---|---|---|
| Cumulative sum per group | df.groupby("k").v.cumsum() | F.sum("v").over(Window.partitionBy("k").orderBy("d").rowsBetween(Window.unboundedPreceding, 0)) |
| Rank within group | df.groupby("k").v.rank(method="first") | F.row_number().over(Window.partitionBy("k").orderBy("v")) |
| Previous row | df.groupby("k").v.shift(1) | F.lag("v", 1).over(Window.partitionBy("k").orderBy("d")) |
| Rolling mean | df.v.rolling(3).mean() | F.avg("v").over(Window.orderBy("d").rowsBetween(-2, 0)) |
| Group total on each row | df.groupby("k").v.transform("sum") | F.sum("v").over(Window.partitionBy("k")) |
| Uppercase | df.s.str.upper() | F.upper("s") |
| Contains | df.s.str.contains("abc") | F.col("s").contains("abc") or F.col("s").rlike("abc") |
| Regex replace | df.s.str.replace(r"\d+", "", regex=True) | F.regexp_replace("s", r"\d+", "") |
| Split | df.s.str.split(",") | F.split("s", ",") |
| Concatenate | df.a + "-" + df.b | F.concat_ws("-", "a", "b") |
| Parse a date | pd.to_datetime(df.d) | F.to_date("d", "yyyy-MM-dd") / F.to_timestamp("d") |
| Date part | df.d.dt.year | F.year("d") |
| Format a date | df.d.dt.strftime("%Y-%m") | F.date_format("d", "yyyy-MM") |
| Date arithmetic | df.d + pd.Timedelta(days=7) | F.date_add("d", 7) |
| Difference in days | (a - b).dt.days | F.datediff("a", "b") |
| Current date | pd.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
# 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()| Task | pandas | PySpark |
|---|---|---|
| Row-wise apply | df.apply(f, axis=1) | No direct equivalent — express it with columns, or use mapInPandas |
| Iterate rows | for _, 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
| Symptom | Cause |
|---|---|
| Results differ between runs | No orderBy. Spark makes no ordering promise, and partition scheduling varies. |
| Notebook cell is instant, next cell takes 20 minutes | Laziness — the earlier cell only built a plan. The action pays for all of it. |
| The same query gets slower each loop iteration | The lineage is re-executed every action. cache() the reused DataFrame, or write it out and read it back. |
| NULL comparisons behave oddly | SQL three-valued logic: NULL = NULL is NULL, not True. Use isNull() or the null-safe eqNullSafe(). |
| NaN and NULL behave differently | Spark keeps them distinct: F.isnan() is not isNull(). pandas conflates the two. |
| Column not found, but it is right there | Spark 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 ambiguous | Both sides of a join contributed a column with that name. Alias the DataFrames or join on a name list. |
| Overwrite deleted more than expected | mode("overwrite") replaces the whole output path. Set spark.sql.sources.partitionOverwriteMode=dynamic to replace only the partitions being written. |
| Thousands of tiny output files | One output file per partition. coalesce() before writing, or repartition by the partition column. |
| A UDF that worked locally fails on the cluster | The 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.