【问题标题】:Split Array of Strings in a DataFrame into their own columns将 DataFrame 中的字符串数组拆分为它们自己的列
【发布时间】:2019-10-20 04:15:25
【问题描述】:

我有一个这样的数据框:

df.show()

+-----+ 
|col1 | 
+-----+ 
|[a,b]| 
|[c,d]|   
+-----+ 

如何将其转换为如下所示的数据框

+----+----+ 
|col1|col2| 
+----+----+ 
|   a|   b| 
|   c|   d|  
+----+----+ 

【问题讨论】:

  • list 的长度是否固定?

标签: json dataframe apache-spark pyspark explode


【解决方案1】:

这取决于你的“列表”的类型:

如果是ArrayType()类型:

df = spark.createDataFrame(spark.sparkContext.parallelize([['a', ["a","b","c"]], ['b', ["d","e","f"]]]), ["key", "col"])
df.printSchema()
df.show()
root
 |-- key: string (nullable = true)
 |-- col: array (nullable = true)
 |    |-- element: string (containsNull = true)
+---+---------+
|key|      col|
+---+---------+
|  a|[a, b, c]|
|  b|[d, e, f]|
+---+---------+
  • 您可以像使用 python 一样使用 [] 访问这些值:
df.select("key", df.col[0], df.col[1], df.col[2]).show()
+---+------+------+------+
|key|col[0]|col[1]|col[2]|
+---+------+------+------+
|  a|     a|     b|     c|
|  b|     d|     e|     f|
+---+------+------+------+
  • 如果它是StructType() 类型:(也许你是通过读取 JSON 来构建数据框的)
df2 = df.select("key", F.struct(
        df.col[0].alias("col1"), 
        df.col[1].alias("col2"), 
        df.col[2].alias("col3")
    ).alias("col"))
df2.printSchema()
df2.show()

root
 |-- key: string (nullable = true)
 |-- col: struct (nullable = false)
 |    |-- col1: string (nullable = true)
 |    |-- col2: string (nullable = true)
 |    |-- col3: string (nullable = true)
+---+---------+
|key|      col|
+---+---------+
|  a|[a, b, c]|
|  b|[d, e, f]|
+---+---------+
  • 您可以使用* 直接“拆分”列:
df2.select('key', 'col.*').show()

+---+----+----+----+
|key|col1|col2|col3|
+---+----+----+----+
|  a|   a|   b|   c|
|  b|   d|   e|   f|
+---+----+----+----+

【讨论】:

  • 谢谢,它确实是由 JSON 构建的,它是一个 ArrayType。您的答案的第一部分有所帮助。但是,您的答案中的 StructType 列的内容不会像 [(col1=a),(col2:b),(col3:c)] 吗?
  • @Gadam 我正在从现有数据框中创建它。如果你看到这就是我访问上面这些元素的方式
猜你喜欢
  • 2016-11-21
  • 2022-12-29
  • 2020-11-10
  • 2017-01-07
  • 2021-10-18
  • 2021-11-17
  • 1970-01-01
相关资源
最近更新 更多