Renaming, casting & inspecting columns
Apache Spark · DataFrames
Theory
Raw data often arrives with short or messy column names and everything typed as strings, so cleaning starts with three simple operations. withColumnRenamed('cust', 'customer') renames one column, withColumnsRenamed({...}) renames several in one call, toDF(*names) renames all by position, and alias() renames inside a select. cast('int'), cast('double') or cast('date') change a column's type, and drop('col') removes columns you no longer need.
With ANSI mode on (the default in recent Spark), casting a bad value such as 'abc' to DOUBLE raises an error instead of quietly returning NULL, so use try_cast when bad values are expected and you want NULL. To inspect a DataFrame, printSchema() and dtypes show the types, describe() returns count, mean, stddev, min and max, and summary() adds percentiles such as 25%, 50% and 75%. For example, casting amounts '55000', '30000', '1500', 'abc' with try_cast gives 3 valid values with a median of 30000.
Why we use it
Almost every pipeline begins by giving columns clear names and correct types; wrong types break joins, sorting and aggregations, and string numbers sort as text. Quick profiling with describe() and summary() catches bad data before it reaches reports.
When to use it
Rename and cast right after reading raw data, ideally by reading with an explicit schema. Use try_cast for dirty inputs and then count the NULLs it produced. Use describe() or summary() for a quick profile; for large tables, profile a sample or selected columns because it scans the data.
How it works
- Raw DataFrame with short names and string columns
- Rename columns to clear, consistent names
- Can some values fail to convert? Yes: Use try_cast and count the NULLs. No: Use cast().
- Drop columns that are no longer needed
- Check printSchema() / dtypes
- Profile with describe() or summary()
Syntax
df.withColumnRenamed("old", "new")
df.withColumnsRenamed({"a": "x", "b": "y"})
df.toDF("id", "name", "city")
df.withColumn("id", F.col("id").cast("int"))
F.expr("try_cast(amount AS DOUBLE)")
df.drop("col1", "col2")
df.printSchema(); df.dtypes
df.describe("amount").show(); df.summary("count", "min", "50%", "max").show()Example
from pyspark.sql import SparkSession, functions as F
spark = (SparkSession.builder.master("local[2]")
.config("spark.ui.enabled", "false")
.getOrCreate())
raw = spark.createDataFrame([
("101", "Asha", "Jaipur", "55000", "2026-01-05"),
("102", "Ravi", "Pune", "30000", "2026-01-06"),
("103", "Meera", "Jaipur", "1500", "2026-01-06"),
("104", "Karan", "Delhi", "abc", "2026-01-07"),
], "id STRING, cust STRING, city STRING, amt STRING, dt STRING")
# 1) Rename: one column, several at once, or all by position
df = (raw.withColumnRenamed("cust", "customer")
.withColumnsRenamed({"amt": "amount", "dt": "order_date"}))
print(df.columns)
# 2) Cast: string -> proper types. try_cast gives NULL for bad values ("abc")
# (plain cast raises an error under ANSI mode, the Spark 4 default)
typed = (df.withColumn("id", F.col("id").cast("int"))
.withColumn("amount", F.expr("try_cast(amount AS DOUBLE)"))
.withColumn("order_date", F.to_date("order_date")))
print(typed.dtypes)
# 3) Drop columns you no longer need
slim = typed.drop("order_date")
print(slim.columns)
# 4) Inspect: describe() = count/mean/stddev/min/max; summary() adds percentiles
slim.select("amount").describe().show()
slim.select("amount").summary("count", "min", "50%", "max").show()
# Output:
# ['id', 'customer', 'city', 'amount', 'order_date']
# [('id', 'int'), ('customer', 'string'), ('city', 'string'), ('amount', 'double'), ('order_date', 'date')]
# ['id', 'customer', 'city', 'amount']
# +-------+------------------+
# |summary| amount|
# +-------+------------------+
# | count| 3|
# | mean|28833.333333333332|
# | stddev|26769.074196418023|
# | min| 1500.0|
# | max| 55000.0|
# +-------+------------------+
#
# +-------+-------+
# |summary| amount|
# +-------+-------+
# | count| 3|
# | min| 1500.0|
# | 50%|30000.0|
# | max|55000.0|
# +-------+-------+
Key points
- withColumnRenamed for one, withColumnsRenamed for many, toDF for all
- cast() changes type; under ANSI mode bad values raise an error
- try_cast returns NULL for values that cannot be converted
- Renaming a column that does not exist is a silent no-op
- describe(): count, mean, stddev, min, max; summary() adds percentiles
- summary/describe return strings; they scan the data, so sample big tables