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

  1. Raw DataFrame with short names and string columns
  2. Rename columns to clear, consistent names
  3. Can some values fail to convert? Yes: Use try_cast and count the NULLs. No: Use cast().
  4. Drop columns that are no longer needed
  5. Check printSchema() / dtypes
  6. 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

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic