仅从pysparkDataframe中获取那些不为null的字段名

8cdiaqws  于 2021-07-13  发布在  Spark
关注(0)|答案(1)|浏览(496)

我有一个Pypark数据框 df1 . 其printschema()如下所示。

  1. df1.printSchema()
  2. root
  3. |-- parent: struct (nullable = true)
  4. | |-- childa: struct (nullable = true)
  5. | | |-- x: string (nullable = true)
  6. | | |-- y: string (nullable = true)
  7. | | |-- z: string (nullable = true)
  8. | |-- childb: struct (nullable = true)
  9. | | |-- x: string (nullable = true)
  10. | | |-- y: string (nullable = true)
  11. | | |-- z: string (nullable = true)
  12. | |-- childc: struct (nullable = true)
  13. | | |-- x: string (nullable = true)
  14. | | |-- y: string (nullable = true)
  15. | | |-- z: string (nullable = true)
  16. | |-- childd: struct (nullable = true)
  17. | | |-- x: string (nullable = true)
  18. | | |-- y: string (nullable = true)
  19. | | |-- z: string (nullable = true)
  1. df1.show(10,False)
  2. ----------------------------------------------------------------
  3. |parent |
  4. ----------------------------------------------------------------
  5. |[,[x_value, y_value, z_value], ,[x_value, y_value, z_value]] |
  6. ----------------------------------------------------------------

这个 df1.show() 显示childb和childd不为null。
我可以得到所有的子结构字段名,比如(childa,childb,childc,childd)。
而且我只想得到那些不为null的子结构字段名。
下面的方法是将所有子结构字段名放入一个列表中,这满足了我上面的第一个要求。

  1. spark.sql("""select parent.* from df1""").schema.fieldNames()
  2. Output:
  3. [childa, childb, childc, childd]

现在我只想得到那些不为null的子结构字段名。我只希望childb和childd进入一个列表。
预期产量: [childb, childd] 谁能帮我一下吗。

laawzig2

laawzig21#

您可以使用过滤器和计数检查字段是否为空:

  1. non_null_fields = [
  2. field
  3. for field in df.select('parent.*').schema.fieldNames()
  4. if df.filter('parent.%s is null' % field).count() == 0
  5. ]

这给了

  1. ['childb', 'childd']

相关问题