首页 > 解决方案 > Pyspark 数据帧写入和读取更改架构

问题描述

我有一个包含 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-sparkpyspark

解决方案


我们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)

推荐阅读