【问题标题】:How to read a csv with using the schema如何使用模式读取 csv
【发布时间】:2021-12-02 12:32:49
【问题描述】:

我正在尝试使用以下方法在 pyspark 数据框中加载 csv 文件:

spark.read.options(delimiter=';', header=True).csv(file)

但我收到以下错误

AnalysisException: 'Unable to infer schema for CSV. It must be specified manually.;'

我尝试手动插入架构,但它仍然没有加载任何值

customSchema = StructType([
    StructField("aaa", StringType(), True),
    StructField("bbb", IntegerType(), True),
    StructField("ccc", IntegerType(), True)])


spark.read.option('header', 'true').option('delimiter', ';').schema(customSchema).csv(file)


spark.read.load(file, format="csv", header="true", sep=';', schema=customSchema)

我只得到一个带有列名的空数据框

【问题讨论】:

标签: python csv pyspark


【解决方案1】:

对于如下分隔的 CSV 文件。

aaa;bbb;ccc
john;12;14
peter;3;7
sally;8;27

您可以像这样将其读入 pyspark。

from pyspark.sql import types

customSchema = types.StructType([
    types.StructField("aaa", types.StringType(), True),
    types.StructField("bbb", types.IntegerType(), True),
    types.StructField("ccc", types.IntegerType(), True)])

df = spark.read.options(delimiter=';', header=True).csv(inputs, schema=customSchema)

【讨论】:

    猜你喜欢
    • 2020-01-26
    • 2018-03-25
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2022-11-01
    • 2018-09-18
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多