【问题标题】:PySpark - READ csv file with quotesPySpark - 读取带有引号的 csv 文件
【发布时间】:2020-09-07 08:38:08
【问题描述】:

我有如下的 csv 文件

name|age|county|state|country
"alex"john"|"30"|"burlington"|"nj"|"usa"

我使用spark读取csv文件

input_df = spark.read.format('csv').options(header='true', inferSchema='false', sep='|').load('s3://path_to_file')

display(input_df)

输出(不知道为什么我们在 alex"john 周围有引号但在其他字段周围没有)

name        age county     state    country
"alex"john" 30  burlington  nj      usa

预期输出:

name        age county     state    country
alex"john   30  burlington  nj      usa

【问题讨论】:

    标签: csv apache-spark pyspark


    【解决方案1】:

    Spark 选择将所有名称读取为字符串(包括所有引号),因为中间的引号将其丢弃。只需像这样删除第一个和最后一个双引号(阅读后):

    from pyspark.sql import functions as F
    df.withColumn("name", F.expr("""substring(name,2,length(name)-2)""")).show()
    
    #+---------+---+----------+-----+-------+
    #|name     |age|county    |state|country|
    #+---------+---+----------+-----+-------+
    #|alex"john|30 |burlington|nj   |usa    |
    #+---------+---+----------+-----+-------+
    

    为了做到dynamically for all columns,,我建议像这样的正则表达式:

    from pyspark.sql import functions as F
    df.select(*[F.regexp_replace(x,'^\"|\"$','').alias(x) for x in df.columns]).show()
    
    #+---------+---+----------+-----+-------+
    #|name     |age|county    |state|country|
    #+---------+---+----------+-----+-------+
    #|alex"john|30 |burlington|nj   |usa    |
    #+---------+---+----------+-----+-------+
    

    【讨论】:

    • 实时,我不知道列名,这需要为所有列动态处理。
    • 假设我输入如下。 ``` name|age|county|state|country "alex\"john"|"30"|"burlington"|"nj"|"usa"``` .. 我如何使用转义字符来避免这种情况正则表达式?
    【解决方案2】:

    这是一个棘手的问题,因为没有什么东西可以逃脱内部引号(例如“\”)。

    如果您没有找到转义内部引号的方法,我建议您按原样读取数据并使用 regex_replace 函数修剪周围的引号,如下所示:

    from pyspark.sql.functions import regexp_replace
    df = spark.read.option("delimiter", "|").option("inferSchema", "true").option("header", "true").csv("tmp.csv")
    df.withColumn("formatted_name", regexp_replace(df.name, '^\"|\"$', "")).show()
    
    

    输出:

    +-----------+---+----------+-----+-------+--------------+
    |       name|age|    county|state|country|formatted_name|
    +-----------+---+----------+-----+-------+--------------+
    |"alex"john"| 30|burlington|   nj|    usa|     alex"john|
    +-----------+---+----------+-----+-------+--------------+
    

    【讨论】:

    • 实时,我不知道列名,这需要为所有列动态处理
    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2019-03-28
    • 2017-06-24
    • 2014-08-27
    相关资源
    最近更新 更多