【问题标题】:Extract columns from a list of lists in pyspark从 pyspark 中的列表列表中提取列
【发布时间】:2020-12-18 03:30:32
【问题描述】:

我一直在尝试从列表列表中提取列,但无法想象如何做到这一点。我对火花相当陌生。在 Spark 2.4.3 上运行 pyspark。

我有一个这样组织的 json:

{ "meta" : { ... },
  "data" : 
  [[ "a", 0, null, "{ }"],
   [ "b", 0, null, "{ }"],
   [ "c", 0, null, "{ }"],
   ] }

我想将“数据”部分放入列中,例如

 +------+------+------+------+
 | col1 | col2 | col3 | col4 |
 +------+------+------+------+
 |   a  |   0  | None | "{ }"|
 |   b  |   0  | None | "{ }"|
 |   c  |   0  | None | "{ }"|

我读入了我的数据框,printSchema() 显示了这一点。

root
 |-- data: array (nullable = true)
 |    |-- element: array (containsNull = true)
 |    |    |-- element: string (containsNull = true)
 |-- meta: struct (nullable = true)
 |    |-- view: struct (nullable = true)
 |    |    |-- approvals: array (nullable = true) ...

我的粗略形状是 70 列 x 650k 行。

我能够爆炸 df 得到 data 部分,但被困在那里。

【问题讨论】:

标签: dataframe apache-spark pyspark apache-spark-sql


【解决方案1】:

先分解行,然后在 Python 中使用[] 选择数组元素。

df2 = df.select(F.explode('data').alias('data')) \
        .select(*[F.col('data')[i].alias('col%s'%(i+1)) for i in range(4)])

df2.show()
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
|   a|   0|null| { }|
|   b|   0|null| { }|
|   c|   0|null| { }|
+----+----+----+----+

【讨论】:

    【解决方案2】:

    为什么不只使用 SparkSession.createDataFrame() 方法?

    https://spark.apache.org/docs/2.4.3/api/python/pyspark.sql.html#pyspark.sql.SparkSession.createDataFrame

    您可以为此方法提供数据和架构参数并获取火花数据帧。

    例子:

    from pyspark.sql import SparkSession
    
    sparkSession = SparkSession.builder.getOrCreate()
    df = sparkSession.createDataFrame(data)
    

    如果 spark 无法从数据中推断架构,则还需要提供架构

    from pyspark.sql.types import StructType
    
    struct = StructType()
    struct.add("col1", "string", True)
    struct.add("col2", "integer", True)
    struct.add("col3", "string", True)
    struct.add("col4", "string", True)
    
    
    df = sparkSession.createDataFrame(data=data, schema=struct)
    

    此外,您可以使用 pyspark 类型类代替 python 原始类型名称。 https://spark.apache.org/docs/2.4.3/api/python/pyspark.sql.html#module-pyspark.sql.types

    模块包含简单类型(StringType, IntegerType, ...)和复杂类型(ArrayType, MapType, ...)

    最后注意:数据不能包含null,在python中应该是None。 spark DataFrame.show() 会将None 列打印为null

    【讨论】:

    • 我不想指定架构,因为我有 70 列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    相关资源
    最近更新 更多