【问题标题】:pySpark not able to handle Multiline string in CSV file while selecting columnspySpark 在选择列时无法处理 CSV 文件中的多行字符串
【发布时间】:2023-02-05 12:17:58
【问题描述】:

我正在尝试使用 pyspark 代码加载如下所示的 csv 文件。

A^B^C^D^E^F
"Yash"^"12"^""^"this is first record"^"nice"^"12"
"jay"^"13"^""^"
In second record, I am new line at the beingnning"^"nice"^"12"
"Nova"^"14"^""^"this is third record"^"nice"^"12"

当我阅读这个文件并选择几列时,整个数据框都被弄乱了。

import pyspark.sql.functions as F

df = (
    spark.read
    .option("delimiter", "^")
    .option('header',True) \
    .option("multiline", "true")
    .option('multiLine', True) \
    .option("escape", "\"")
    .csv(
        "test3.csv",
        header=True,
    )
)
df.show()
df = df.withColumn("isdeleted", F.lit(True))
select_cols = ['isdeleted','B','D','E','F']
df = new_df.select(*select_cols)
df.show()

(为了代码的可读性截断了一些导入语句)

这是我在上面的代码运行时看到的


Before column selection (entire DF)
+----+---+----+--------------------+----+---+
|   A|  B|   C|                   D|   E|  F|
+----+---+----+--------------------+----+---+
|Yash| 12|null|this is first record|nice| 12|
| jay| 13|null|\nIn second recor...|nice| 12|
|Nova| 14|null|this is third record|nice| 12|
+----+---+----+--------------------+----+---+


After df.select(*select_cols)
+---------+----+--------------------+----+----+
|isdeleted|   B|                   D|   E|   F|
+---------+----+--------------------+----+----+
|     true|  12|this is first record|nice|  12|
|     true|  13|                null|null|null|
|     true|nice|                null|null|null|
|     true|  14|this is third record|nice|  12|
+---------+----+--------------------+----+----+

在这里,带有换行符的第二行被分解为 2 行,输出文件也像我上面显示的数据帧预览一样混乱。

我正在使用使用 spark 3.3.0 版本的 apache Glue image amazon/aws-glue-libs:glue_libs_4.0.0_image_01。还尝试使用 spark 3.1.1。我在两个版本中都看到了同样的问题。

我不确定这是 spark 包中的错误还是我在这里遗漏了一些东西。任何帮助将不胜感激

【问题讨论】:

  • 不会发生在我身上,我使用了那个问题中提供的相同代码,工作正常。我正在使用火花 3.3.0
  • @TusharPatil 你能再帮我验证一次吗?有 2 个 df.show() 语句不要混淆,第一个将显示正确的列顺序。第二个是搞砸的地方

标签: dataframe apache-spark pyspark aws-glue


【解决方案1】:

你给了错误的转义字符。它通常是 并且您在报价中指定了它。更改选项后,

df = spark.read.csv('test.csv', sep='^', header=True, multiLine=True)
df.show()

df.select('B').show()

+----+---+----+--------------------+----+---+
|   A|  B|   C|                   D|   E|  F|
+----+---+----+--------------------+----+---+
|Yash| 12|null|this is first record|nice| 12|
| jay| 13|null|
In second recor...|nice| 12|
|Nova| 14|null|this is third record|nice| 12|
+----+---+----+--------------------+----+---+

+---+
|  B|
+---+
| 12|
| 13|
| 14|
+---+

你会得到想要的结果。

【讨论】:

    猜你喜欢
    • 2016-03-07
    • 1970-01-01
    • 2021-01-21
    • 2019-06-28
    • 2021-07-21
    • 2019-11-06
    • 1970-01-01
    • 2020-05-22
    • 2010-09-05
    相关资源
    最近更新 更多