【问题标题】:Find latest non null value for each row in PySpark在 PySpark 中为每一行查找最新的非空值
【发布时间】:2019-08-29 10:51:04
【问题描述】:

我有一个像这样的 PySpark 数据框,

+----------+------+------+------+------+------+------+------+------+------+------+------+------+------+
|id        |201806|201807|201808|201809|201810|201811|201812|201901|201902|201903|201904|201905|201906|
+----------+------+------+------+------+------+------+------+------+------+------+------+------+------+
|  1       |    15|    15|    15|    15|    15|    15|    15|    15|    15|  null|    15|    15|    15|
|  2       |     4|     4|     4|     4|     4|     4|     4|     4|     4|     4|     4|     4|     4|
|  3       |     7|     7|     7|     7|     7|     7|     7|     7|  null|  null|  null|  null|  null|
-------------------------------------------------------------------------------------------------------

从这些数据中,我想为每一行找到最新的非空值。

我希望得到以下结果。

+----------+------+
|id.         |latest|
+----------+------+
|  1       |    15| 
|  2       |     4|  
|  3       |     7|  
-------------------

我关注了这个answer,但我无法按行执行操作。

我用过,

df.select([last(x, ignorenulls=True).alias(x) for x in df.columns])

但此代码仅按列执行,我希望按行执行相同的操作。

【问题讨论】:

  • 你尝试过什么?
  • 我已经更新了......

标签: python pyspark


【解决方案1】:

假设您的列是从最旧到最新排序的,您可以使用下面使用coalesce 的代码来获取最新值。

from pyspark.sql.functions import coalesce

df.select('id', coalesce(*[i for i in df.columns[::-1] if i != 'id']).alias('latest')).show()

输出:

+---+------+
| id|latest|
+---+------+
|  1|    15|
|  2|     4|
|  3|     7|
+---+------+

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2016-08-20
    • 2016-04-26
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多