python - Pyspark:将具有嵌套结构的数组转换为字符串

标签 python sql apache-spark pyspark spark-dataframe

我有一个名为 Filters 的 pyspark 数据框: “数组>”

我想将我的数据框保存在 csv 文件中,为此我需要将数组转换为字符串类型。

我尝试转换它:DF.Filters.tostring()DF.Filters.cast(StringType()),但是这两种解决方案都会为每个解决方案生成错误消息列过滤器中的行:

org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@56234c19

代码如下

from pyspark.sql.types import StringType

DF.printSchema()

|-- ClientNum: string (nullable = true)
|-- Filters: array (nullable = true)
    |-- element: struct (containsNull = true)
          |-- Op: string (nullable = true)
          |-- Type: string (nullable = true)
          |-- Val: string (nullable = true)

DF_cast = DF.select ('ClientNum',DF.Filters.cast(StringType())) 

DF_cast.printSchema()

|-- ClientNum: string (nullable = true)
|-- Filters: string (nullable = true)

DF_cast.show()

| ClientNum | Filters 
|  32103    | org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@d9e517ce
|  218056   | org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@3c744494

示例 JSON 数据:

{"ClientNum":"abc123","Filters":[{"Op":"foo","Type":"bar","Val":"baz"}]}

谢谢!!

最佳答案

我创建了一个示例 JSON 数据集来匹配该模式:

{"ClientNum":"abc123","Filters":[{"Op":"foo","Type":"bar","Val":"baz"}]}

select(s.col("ClientNum"),s.col("Filters").cast(StringType)).show(false)

+---------+------------------------------------------------------------------+
|ClientNum|Filters                                                           |
+---------+------------------------------------------------------------------+
|abc123   |org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@60fca57e|
+---------+------------------------------------------------------------------+

最好使用展开数组的 explode() 函数解决您的问题,然后使用星号扩展符号:

s.selectExpr("explode(Filters) AS structCol").selectExpr("structCol.*").show()
+---+----+---+
| Op|Type|Val|
+---+----+---+
|foo| bar|baz|
+---+----+---+

要使其成为以逗号分隔的单列字符串:

s.selectExpr("explode(Filters) AS structCol").select(F.expr("concat_ws(',', structCol.*)").alias("single_col")).show()
+-----------+
| single_col|
+-----------+
|foo,bar,baz|
+-----------+

分解数组引用:Flattening Rows in Spark

“结构”类型的星号扩展引用:How to flatten a struct in a spark dataframe?

关于python - Pyspark:将具有嵌套结构的数组转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43347098/

相关文章:

python - 如何在openerp中多次继承一个类?

sql - 在 SQL Server 存储过程中声明一个变量列表

sql - 数据库表的行和列的转换

mysql - 插入新值时使用同一 ID 中的数字插入另一个字段

python - 在python脚本之间发送字符串

python - 将任务安排为从同步代码运行事件循环

apache-spark - 用 null 替换空字符串会导致数据帧大小增加吗?

python - Apache-spark - 在 Windows 上启动 pyspark 时出错

python - psycopg2.DataError : invalid input syntax for integer: "test" Getting error when moving code to test server

scala - Spark DataFrame 将 struct<.. 包装到 struct<. 的数组中