如何拆分包含字符串的数据框列

时间:2018-09-22 16:36:03

标签: apache-spark dataframe pyspark user-defined-functions explode

我正在使用spark 2.2和 我正在尝试从tss文件中读取数据集,例如pyspark中的以下内容:

    student_id subjects result
    "1001" "[physics, chemistry]" "pass"
    "1001" "[biology, math]" "fail"
    "1002" "[economics]" "pass"
    "1002" "[physics, chemistry]" "fail"

我想要以下结果:

    student_id subject result
    "1001" "physics" "pass"
    "1001" "chemistry" "pass"
    "1001" "biology" "fail"
    "1001" "math" "fail"
    "1002" "economics" "pass"
    "1002" "physics" "fail"
    "1002" "chemistry" "fail"

我做了以下事情,但似乎不起作用

    df = spark.read.format("csv").option("header", "true").option("mode", "FAILFAST") \
    .option("inferSchema", "true").option("sep", ' ').load("ds3.tsv")
    df.printSchema()

当我执行“ printSchema”时,看到以下结果

   root
    |-- student_id: integer (nullable = true)
    |-- subjects: string (nullable = true)
    |-- result: string (nullable = true)

当我执行以下操作时,即使用爆炸功能:

    df.withColumn("subject", explode(col("subjects"))).select("student_id", "subject", "result").show(2)

我收到以下异常:

    AnalysisException: "cannot resolve 'explode(`subjects`)' due to data type mismatch: input to function explode should be array or map type, not string;;\n'Project [student_id#10, subjects#11, results#12, explode(subjects#11) AS subject#30]\n+- AnalysisBarrier\n      +- Relation[student_id#10,subjects#11,result#12] csv\n"

我读到某处pyspark不支持字符串的ArrayType。

编写一个UDF,将其从“主题”列值的两端剪掉“ []”字符,然后使用“ split”功能并使用“ explode”是个好主意吗?

1 个答案:

答案 0 :(得分:1)

第二列是字符串,可以拆分,然后使用“爆炸”:

val df = List(
  ("1001", "[physics, chemistry]", "pass"),
  ("1001", "[biology, math]", "fail"),
  ("1002", "[economics]", "pass"),
  ("1002", "[physics, chemistry]", "fail")
).toDF("student_id", "subjects", "result")

df
  .withColumn("clearedFromLeftBracket", expr("substring(subjects,2,length(subjects))"))
  .withColumn("clearedFromBrackets", expr("substring(clearedFromLeftBracket,1,length(clearedFromLeftBracket)-1)"))
  .withColumn("splitted", split($"clearedFromBrackets", ", "))
  .withColumn("subjectResult", explode($"splitted"))
  .drop("clearedFromLeftBracket", "clearedFromBrackets", "splitted","subjects")

输出:

+----------+------+-------------+
|student_id|result|subjectResult|
+----------+------+-------------+
|1001      |pass  |physics      |
|1001      |pass  |chemistry    |
|1001      |fail  |biology      |
|1001      |fail  |math         |
|1002      |pass  |economics    |
|1002      |fail  |physics      |
|1002      |fail  |chemistry    |
+----------+------+-------------+