TECHNOLOGIESTieInn Technologies

DataFrame basics

Spark / PySpark · 14 questions

Short notes

Key idea

A Spark DataFrame is a distributed table with a schema. You read it, select and create columns with functions from pyspark.sql.functions, and write it out. Each call returns a new DataFrame.

Syntax

from pyspark.sql import functions as F
df = spark.read.option("header", True).csv("orders.csv", inferSchema=True)
df.printSchema(); df.show(5)
df.select("city", "amount")
df.withColumn("tax", F.col("amount") * 0.18)
df.filter((F.col("city") == "Chennai") & (F.col("amount") > 500))
df.withColumnRenamed("amt", "amount").drop("notes")
df.write.mode("overwrite").parquet("out/orders")

Example

clean = (df.filter(F.col("amount").isNotNull())
           .withColumn("order_date", F.to_date("order_ts")))
clean.groupBy("order_date").count().show()

The chain drops rows with no amount, adds a proper date column, then counts orders per day. Only show() makes Spark actually read the file and do the work.

Traps

  • DataFrames are immutable; df.withColumn(...) alone changes nothing; assign the result.
  • inferSchema scans the data and guesses; give an explicit schema for big or messy files.
  • Use &, |, ~ with brackets in filters, as in pandas.
  • mode("overwrite") replaces the whole output folder.

Want the full lesson with step-by-step examples, a project and a certificate? Spark / PySpark course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    DataFrame basics

  1. Question 1easy

    You run df.withColumn("x", F.lit(1)) on its own line. Does df now have column x?

  2. DataFrame basics

  3. Question 2medium

    Which filter keeps delivered orders above 1000?

  4. DataFrame basics

  5. Question 3medium

    What does this print?

    df = spark.createDataFrame(
        [(1, "Chennai"), (1, "Madurai"), (2, "Chennai"), (2, "Chennai")],
        ["customer_id", "city"])
    print(df.dropDuplicates(["customer_id"]).count(), df.distinct().count())
  6. DataFrame basics

  7. Question 4medium

    You need to upper-case a city column. What's the best approach?

  8. DataFrame basics

  9. Question 5easy

    You read a CSV with spark.read.option("header", True).csv(path) and no other options. What type are the numeric columns?

9 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.