You'll create DataFrames four common ways. First, spark.range(n) — a one-column DataFrame of id from 0 to n-1, perfect for quick experiments:
Signature
def range(end: Long): Dataset[Row]
def range(start: Long, end: Long): Dataset[Row]
def range(start: Long, end: Long, step: Long): Dataset[Row]
Scala
spark.range(5).show()
spark.range(5) → ids 0..4
baked output — Spark-only type, not runnable in the browser engine
Second, from a Scala Seq of tuples with toDF — the fastest way to hand-build test data:
Scala
val people = Seq(
(1, "Aisha", "India", 29, "2025-02-11"),
(2, "Rohan", "India", 34, "2024-11-03"),
(3, "Mia", "USA", 41, "2025-06-20"),
(4, "Liam", "UK", 23, "2025-01-08"),
(5, "Noah", "Canada", 37, "2024-08-15")
).toDF("id", "name", "country", "age", "signup_date")
people.show()Run the equivalent Spark SQL — edit it and press Run
Third, with an explicit StructType schema when you need exact types (and control over nullability) instead of letting Spark infer them:
Scala
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
val schema = StructType(Seq(
StructField("id", IntegerType, nullable = false),
StructField("name", StringType, nullable = true),
StructField("country", StringType, nullable = true),
StructField("age", IntegerType, nullable = true)
))
val rows = Seq(Row(1, "Aisha", "India", 29), Row(2, "Rohan", "India", 34))
val df = spark.createDataFrame(spark.sparkContext.parallelize(rows), schema)
df.printSchema()printSchema() output
baked output — Spark-only type, not runnable in the browser engine
Fourth — how you'll actually load data in production — from files: spark.read.csv / json / parquet. Give it a schema or ask it to infer one:
Scala
val orders = spark.read
.option("header", "true")
.option("inferSchema", "true")
.csv("s3://bucket/orders/")
// or, columnar + schema baked in:
val o2 = spark.read.parquet("s3://bucket/orders_parquet/")inferSchema makes Spark read the file twice and it often guesses wrong (dates become strings, ints become doubles). For anything real, pass an explicit
schema(...) or use a self-describing format like Parquet. We go deep on this in the
Parquet vs ORC vs Avro guide.