apache-spark - 在 Spark 中读取 CSV 文件时如何忽略双引号?

标签 apache-spark pyspark

我有一个 CSV 文件,如:

col1,col2,col3,col4
"A,B","C", D"

我想将它作为 spark 中的数据框读取,其中每个字段的值都与 CSV 中写入的完全相同(我想将 " 字符视为常规字符,并像任何其他字符一样复制它)。

预期输出:
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
|  "A|  B"| "C"|  D"|
+----+----+----+----+

我得到的输出:
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
| A,B|   C|  D"|null|
+----+----+----+----+

在pyspark中,我是这样读的:
dfr = spark.read.format("csv").option("header", "true").option("inferSchema", "true")

我知道如果我添加这样的选项:
dfr.option("quote", "\u0000")
我在上面的例子中得到了预期的结果,作为 char '"' 的函数现在由 '\u0000' 完成,但如果我的 CSV 文件包含 '\u0000' char,我也会得到错误的结果。

因此,我的问题是:
如何禁用引用选项,以便没有字符像引用一样?

我的 CSV 文件可以包含任何字符,我希望所有字符(除逗号外)都可以简单地复制到它们各自的数据框单元格中。我想知道是否有办法使用转义选项来完成此操作。

最佳答案

来自 pyspark.sql.DataFrameReader.csv 的文档(强调我的):

quote – sets a single character used for escaping quoted values where the separator can be part of the value. If None is set, it uses the default value, ". If you would like to turn off quotations, you need to set an empty string.



dfr = spark.read.csv(
    path="path/to/some/file.csv",
    header="true",
    inferSchema="true",
    quote=""
)
dfr.show()
#+----+----+----+----+
#|col1|col2|col3|col4|
#+----+----+----+----+
#|  "A|  B"| "C"|  D"|
#+----+----+----+----+

关于apache-spark - 在 Spark 中读取 CSV 文件时如何忽略双引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54523324/

相关文章:

postgresql - Azure Databrick 平台上的 pyspark 中的 Py4JJava 错误

apache-spark - pyspark.sql.utils.AnalysisException : Parquet data source does not support void data type

python - 如何将稀疏数据的PythonRDD转换为密集的PythonRDD

apache-spark - 如何从Apache Spark中的外部文本文件读取structType模式?

apache-spark - 如何在 Kubernetes 上使用 Spark 修复 "Forbidden!Configured service account doesn' t have access”?

scala - 如何在spark/scala中将excel数据读入数据框

apache-spark - Spark SQL 是否计数不正确或我无法正确编写 SQL?

scala - 无法使用 case 类从 Row 的 RDD 创建数据框

apache-spark - 如何将每个 DStream 保存/插入到永久表中

python - 使用 Python 的 reduce() 连接多个 PySpark DataFrame