【问题标题】:Pyspark dataframe write and read changes schemaPyspark 数据帧写入和读取更改架构
【发布时间】:2020-07-28 20:52:39
【问题描述】:

我有一个包含 string 和 int 列的 spark 数据框。

但是当我将数据框写入 csv 文件并稍后加载时,所有列都作为字符串加载。

from pyspark.sql import SparkSession
spark = SparkSession.builder.enableHiveSupport().getOrCreate()
df = spark.createDataFrame([("Alberto", 2), ("Dakota", 2)], 
                              ["Name", "count"])

之前:

df.printSchema()

输出:

root
  |-- Name: string (nullable = true)
  |-- count: long (nullable = true)


df.write.mode('overwrite').option('header', True).csv(filepath)

new_df = spark.read.option('header', True).csv(filepath)

之后:

new_df.printSchema()

输出:

root
  |-- Name: string (nullable = true)
  |-- count: string (nullable = true)

如何在编写时指定存储模式?

【问题讨论】:

    标签: apache-spark pyspark


    【解决方案1】:

    我们在写作时don't have to specify schema,但我们可以在阅读时指定schema

    Example:

    from pyspark.sql.types import *
    from pyspark.sql.functions import *
    schema = StructType(
       [
         StructField('Name', StringType(), True),
        StructField('count', LongType(), True)
       ]
     )
    
    #specify schema while reading
    new_df = spark.read.schema(schema).option('header', True).csv(filepath)
    new_df.printSchema()
    
    #or else use inferschema option as true but specifying schema will be more robust
    new_df = spark.read.option('header', True).option("inferSchema",True).csv(filepath)
    

    【讨论】:

    • 我在加载文件时事先并不知道所有的列名。我可以将一列指定为字符串,然后将所有其他列默认为长吗?
    • @ThirupathiThangavel,那么最好使用inferSchema 选项,在这种情况下我们不需要知道之前的所有列名(或)否则您需要动态构建架构 然后在使用 .schema 选项读取 csv 文件时传递架构。
    猜你喜欢
    • 2020-10-06
    • 2018-06-24
    • 2020-11-26
    • 2023-02-21
    • 1970-01-01
    • 2017-11-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多