Apache spark 在pyspark中,如何平均以null分隔的数字块?

Apache spark 在pyspark中,如何平均以null分隔的数字块?,apache-spark,pyspark,apache-spark-sql,Apache Spark,Pyspark,Apache Spark Sql,给定的是以下pyspark数据帧,其中顺序由ID给出: 身份证件 年龄 1. 无效的 2. 10 3. 90 4. 无效的 5. 无效的 6. 无效的 7. 20 8. 30 9 70 10 无效的 可以使用lag检查前一行是否为空,如果当前行不为空,则可以将其标记为块的开始。然后,对这些标志求和,就可以得到所需的块号 from pyspark.sql import functions as F, Window df2 = df.withColumn( 'block', (~F

给定的是以下pyspark数据帧,其中顺序由ID给出:

身份证件 年龄 1. 无效的 2. 10 3. 90 4. 无效的 5. 无效的 6. 无效的 7. 20 8. 30 9 70 10 无效的
可以使用
lag
检查前一行是否为空,如果当前行不为空,则可以将其标记为块的开始。然后,对这些标志求和,就可以得到所需的块号

from pyspark.sql import functions as F, Window

df2 = df.withColumn(
    'block',
    (~F.col('age').isNull() & F.lag('age').over(Window.orderBy('ID')).isNull()).cast('int')
).withColumn(
    'block',
    F.when(~F.col('age').isNull(), F.sum('block').over(Window.orderBy('ID')))
)

df2.show()
+---+----+-----+
| ID| age|block|
+---+----+-----+
|  1|null| null|
|  2|  10|    1|
|  3|  90|    1|
|  4|null| null|
|  5|null| null|
|  6|null| null|
|  7|  20|    2|
|  8|  30|    2|
|  9|  70|    2|
| 10|null| null|
+---+----+-----+
然后可以进行聚合:

df3 = (df2.filter('block is not null')
          .groupBy('block')
          .agg(F.min('ID').alias('First_ID'), F.max('ID').alias('Last_ID'), F.avg('age').alias('avg_age'))
          .drop('block')
      )

df3.show()
+--------+-------+-------+
|First_ID|Last_ID|avg_age|
+--------+-------+-------+
|       2|      3|   50.0|
|       7|      9|   40.0|
+--------+-------+-------+