從理論上講,這個解決方案非常適合我的需要,即創建數據幀的新復制版本,同時排除某些嵌套的結構字段。這是我的問題的最低限度可重現的工件:>>> df.printSchema()root| -- big: array(nullable=true)| | -- element: struct(containsNull=true)| | | -- keep: string(nullable=true)| | | -- delete: string(nullable=true)您可以像這樣實例化它:schema = StructType([StructField("big", ArrayType(StructType([ StructField("keep", StringType()), StructField("delete", StringType())])))])df = spark.createDataFrame(spark.sparkContext.emptyRDD(), schema)我的目標是將數據框(以及我要保留的列中的值)轉換為排除某些嵌套結構的數據框,delete例如。root| -- big: array(nullable=true)| | -- element: struct(containsNull=true)| | | -- keep: string(nullable=true)根據我鏈接的嘗試利用 pyspark.sqlto_json和from_json函數的解決方案,它應該可以通過以下方式完成:new_schema = StructType([StructField("big", ArrayType(StructType([ StructField("keep", StringType())])))])test_df = df.withColumn("big", to_json(col("big"))).withColumn("big", from_json(col("big"), new_schema))>>> test_df.printSchema()root| -- big: struct(nullable=true)| | -- big: array(nullable=true)| | | -- element: struct(containsNull=true)| | | | -- keep: string(nullable=true)>>> test_df.show()+----+| big|+----+|null|+----+所以要么我沒有正確地遵循他的指示,要么它不起作用。沒有 udf 怎么辦?
1 回答

慕森王
TA貢獻1777條經驗 獲得超3個贊
它應該可以工作,您只需要調整 new_schema 以僅包含“大”列的元數據,而不是數據框:
new_schema = ArrayType(StructType([StructField("keep", StringType())]))
test_df = df.withColumn("big", from_json(to_json("big"), new_schema))
添加回答
舉報
0/150
提交
取消