【问题标题】:Can't read CSV string using PySpark无法使用 PySpark 读取 CSV 字符串
【发布时间】:2019-11-06 16:46:17
【问题描述】:

场景是: EventHub -> Azure Databricks(使用 pyspark)

文件格式: CSV(引号、管道分隔和自定义架构)

我正在尝试读取来自 eventthub 的 CSV 字符串。 Spark 正在使用正确的架构成功创建数据框,但在每条消息之后数据框都是空的。

我设法在流环境之外进行了一些测试,当从文件中获取数据时,一切顺利,但是当数据来自字符串时,它就失败了。

所以我找到了一些链接来帮助我解决这个问题,但没有一个有效:

can-i-read-a-csv-represented-as-a-string-into-apache-spark-using-spark-csv?rq=1

Pyspark - converting json string to DataFrame

现在我有以下代码:

schema = StructType([StructField("Decisao",StringType(),True), StructField("PedidoID",StringType(),True), StructField("De_LastUpdated",StringType(),True)])
body = 'DECISAO|PEDIDOID|DE_LASTUPDATED\r\n"asdasdas"|"1015905177"|"sdfgsfgd"'
csvData = sc.parallelize([body])

df = spark.read \
.option("header", "true") \
.option("mode","FAILFAST") \
.option("delimiter","|") \
.schema(schema) \
.csv(csvData)

df.show()

CSV 文件也能做到这一点吗?

【问题讨论】:

    标签: python-3.x pyspark azure-databricks


    【解决方案1】:

    您可以通过Rowsplit| 分隔符上构造这样的架构

    from pyspark.sql.functions import *
    from pyspark.sql.types import *
    from pyspark.sql import Row
    body = 'DECISAO|PEDIDOID|DE_LASTUPDATED\r\n"asdasdas"|"1015905177"|"sdfgsfgd"'
    csvData = sc.parallelize([body])
    schemaDF = csvData\
    .map(lambda x: x.split("|"))\
    .map(lambda x: Row(x[0],\
                       x[1],\
                       x[2],\
                       x[3],\
                       x[4]))\
    .toDF(["Decisao", "PedidoID", "De_LastUpdated", "col4", "col5"])
    
    for i in schemaDF.take(1): print(i)
    Row(Decisao='DECISAO', PedidoID='PEDIDOID', De_LastUpdated='DE_LASTUPDATED\r\n"asdasdas"', col4='"1015905177"', col5='"sdfgsfgd"')
    
    schemaDF.printSchema()
    root
     |-- Decisao: string (nullable = true)
     |-- PedidoID: string (nullable = true)
     |-- De_LastUpdated: string (nullable = true)
     |-- col4: string (nullable = true)
     |-- col5: string (nullable = true)
    
    

    【讨论】:

    • 嗯,这不是我所做的,但它有助于找出问题所在。基本上我将 [body] 更改为 body.split('\n') 并且一切正常。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多