簡體   English   中英

PySpark 刪除重復項並保留列中具有最高值的行

[英]PySpark drop Duplicates and Keep Rows with highest value in a column

我有以下 Spark 數據集:

id    col1    col2    col3    col4
1      1        5       2      3
1      1        0       2      3
2      3        1       7      7
3      6        1       3      3
3      6        5       3      3

我想刪除列子集 ['id,'col1','col3','col4'] 中的重復項,並保留 col2 中具有最高值的重復行。 結果應該是這樣的:

id    col1    col2    col3    col4
1      1        5       2      3
2      3        1       7      7
3      6        5       3      3

我怎樣才能在 PySpark 中做到這一點?

分組並獲得col2的最大值?

df = df.groupby(['id','col1','col3','col4']).max('col2')

另一種方法是計算最大值,過濾其中 max=col2。 這允許您保留條件為真的多個實例

df.withColumn('max',max('col2').over(Window.partitionBy('id'))).where(col('col2')==col('max')).show()

如果您更喜歡 SQL 語法而不是 PySpark Dataframe api,您可以采用以下方法:

創建 dataframe(可選,因為您已經有數據)

from pyspark.sql.types import StructType,StructField, IntegerType

data = [
  (1,      1,        5,       2,      3),
  (1,      1,        0,       2,      3),
  (2,      3,        1,       7,      7),
  (3,      6,        1,       3,      3),
  (3,      6,        5,       3,      3),
]

schema = StructType([ \
    StructField("id",IntegerType()), \
    StructField("col1",IntegerType()), \
    StructField("col2",IntegerType()), \
    StructField("col3", IntegerType()), \
    StructField("col4", IntegerType()), \
  ])

df = spark.createDataFrame(data=data,schema=schema)
df.show()

然后創建 dataframe 的視圖以運行 sql 查詢。 下面創建一個名為“tbl”的 dataframe 的新臨時視圖。

# create view from df called "tbl"
df.createOrReplaceTempView("tbl")

最后用視圖寫一個 SQL 查詢。 這里我們按 id、col1、col3 和 col4 分組,然后 select 行的最大值為 col2。

# query to group by id,col1,col3,col4 and select max col2
my_query = """
select 
  id, col1, max(col2) as col2, col3, col4
from tbl
group by id, col1, col3, col4
"""

new_df = spark.sql(my_query)
new_df.show()

最終 output:

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  1|   1|   5|   2|   3|
|  2|   3|   1|   7|   7|
|  3|   6|   5|   3|   3|
+---+----+----+----+----+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM