【问题标题】:Pyspark remove duplicates based on string value from another columnsPyspark 根据其他列中的字符串值删除重复项
【发布时间】:2021-06-21 07:01:29
【问题描述】:

我在下面有这个数据框:

+--------+----------+----------+
|SID     |Date      |Attribute |
+--------+----------+----------+
|1001    |2021-01-01|Y         |
|1001    |2021-05-31|N         |
|1001    |2021-05-15|N         |
|1002    |2021-05-31|N         |
|1002    |2021-04-06|N         |
|1003    |2021-01-01|Y         |
|1003    |2021-02-01|N         |
|1004    |2021-03-30|N         |
+--------+----------+----------+

我正在尝试得到如下结果。

+--------+----------+----------+
|SID     |Date      |Attribute |
+--------+----------+----------+
|1001    |2021-01-01|Y         |
|1002    |2021-05-31|N         |
|1002    |2021-04-06|N         |
|1003    |2021-01-01|Y         |
|1004    |2021-03-30|N         |
+--------+----------+----------+

当重复的SID 在同一行中有YAttribute 时,我想排除该记录,但如果Attribute 中只有N,则保留SID 的记录。

我认为带有过滤器的窗口分区会有所帮助,但我不确定如何在我提到的条件下做到这一点。有什么方法可以在 Pyspark 中实现吗?我看到了一个类似的帖子,但它是针对 Scala SQL 而不是针对 Pyspark。

【问题讨论】:

    标签: pyspark


    【解决方案1】:
    from pyspark.sql import Window
    import pyspark.sql.functions as F
    
    
     #Create a window of each group ordered by Date and containing all elements in a specified column    h=Window.partitionBy('SID').orderBy('Date').rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)
    
       (
     df.withColumn('filt', F.first('Attribute').over(h))# Create a column in which you broadcast first Attribute value in each SID
     
     .filter(F.col('Attribute')==F.col('filt')).drop('filt')#After broadcast, filter where Attribute value equals to the new columns value and drop the new column
    ).show()
    
    
    +----+----------+---------+
    | SID|      Date|Attribute|
    +----+----------+---------+
    |1001|2021-01-01|        Y|
    |1002|2021-04-06|        N|
    |1002|2021-05-31|        N|
    |1003|2021-01-01|        Y|
    |1004|2021-03-30|        N|
    +----+----------+---------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2018-10-13
      • 1970-01-01
      • 2019-05-17
      相关资源
      最近更新 更多