Load Data in CSV Format¶
.load
is a general method for reading data in different format. You have to specify the format of the data via the method.format
of course..csv
(both for CSV and TSV),.json
and.parquet
are specializations of.load
..format
is optional if you use a specific loading function (csv, json, etc.).No header by default.
.coalesece(1)
orrepartition(1)
if you want to write to only 1 file.
In [3]:
import findspark
# A symbolic link of the Spark Home is made to /opt/spark for convenience
findspark.init("/opt/spark")
from pyspark.sql import SparkSession, DataFrame
from pyspark.sql.types import *
from pyspark.sql.functions import *
spark = SparkSession.builder.appName("PySpark").enableHiveSupport().getOrCreate()
Using load
¶
In [4]:
schema = StructType(
[
StructField("denominator", IntegerType(), False),
StructField("max_mod", IntegerType(), False),
StructField("num_distinct", IntegerType(), False),
StructField("max_dup", IntegerType(), False),
StructField("avg_dup", DoubleType(), False),
]
)
In [7]:
flight = (
spark.read.format("csv")
.option("header", "true")
.schema(schema)
.load("../../home/media/data/flights14.csv")
)
flight.show()
Using csv
¶
In [6]:
flight = (
spark.read.option("header", "true")
.schema(schema)
.csv("../../home/media/data/flights14.csv")
)
flight.show()
References¶
https://spark.apache.org/docs/latest/api/python/pyspark.sql.html
https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame
https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column
https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#module-pyspark.sql.functions
In [ ]: