大三寒假学习进度笔记9

今日学习时间一小时,学习内容:通过不同格式构建DataFrame对象,包括基于Pandas的DF转换,读取text,csv,json和jparquet创建。

jparquet具有以下特点:

  • 列式存储
  • 自带Schema
  • 具备Predicate Filter特性

一个Parquet文件的内容由Header、Data Block和Footer三部分组成。

在文件的首尾各有一个内容为PAR1的Magic Number,用于标识这个文件为Parquet文件。Header部分就是开头的Magic Number。

Data Block是具体存放数据的区域,由多个Row Group组成,每个Row Group包含了一批数据。

Footer部分由File Metadata、Footer Length和Magic Number三部分组成。Footer Length是一个4字节的数据,用于标识Footer部分的大小,帮助找到Footer的起始指针位置。Magic Number同样是PAR1。File Metada包含了非常重要的信息,包括Schema和每个Row Group的Metadata。每个Row Group的Metadata又由各个Column的Metadata组成,每个Column Metadata包含了其Encoding、Offset、Statistic信息等等。

接下来是我今日学习过程中使用到的一些代码

# coding:utf8

from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StringType, IntegerType
import pandas as pd

if __name__ == '__main__':
    spark = SparkSession.builder. \
        appName("test"). \
        master("local[*]"). \
        getOrCreate()

    sc = spark.sparkContext

    #text数据源,读取数据的特点是:将一整行只作为一个列读取
    schema = StructType().add("data", StringType(), nullable=True)
    df = spark.read.format("text").\
        schema(schema=schema).\
        load("../data/input/people.txt")



    #json类型自带有Schema信息
    df = spark.read.format("json").load("../data/input/people.json")


    #读取csv格式
    df = spark.read.format("csv").\
        option("sep",";").\
        option("header",True).\
        option("encoding","utf-8").\
        schema("name STRING,age INT, job STRING").\
        load("../data/input/people.csv")



    #读取parquet数据源 自带schema,直接load,其他不需要
    df = spark.read.format("parquet").load("../data/input/users.parquet")

    df.printSchema()
    df.show()

  

posted @ 2024-01-18 21:51  wrf12  阅读(17)  评论(0)    收藏  举报