pyspark中有一个数据帧,数据如下:
user_id object_id score
user_1 object_1 3
user_1 object_1 1
user_1 object_2 2
user_2 object_1 5
user_2 object_2 2
user_2 object_2 6
我期望的是每组中以相同的user_id返回 2 条记录,这些记录需要具有最高分。因此,结果应如下所示:
user_id object_id score
user_1 object_1 3
user_1 object_2 2
user_2 object_2 6
user_2 object_1 5
我真的很陌生 pyspark,任何人都可以给我一个代码片段或这个问题相关文档的门户吗?非常感谢!
我相信您需要使用窗口函数根据user_id
和score
获得每一行的排名,然后过滤结果以仅保留前两个值。
from pyspark.sql.window import Window
from pyspark.sql.functions import rank, col
window = Window.partitionBy(df['user_id']).orderBy(df['score'].desc())
df.select('*', rank().over(window).alias('rank'))
.filter(col('rank') <= 2)
.show()
#+-------+---------+-----+----+
#|user_id|object_id|score|rank|
#+-------+---------+-----+----+
#| user_1| object_1| 3| 1|
#| user_1| object_2| 2| 2|
#| user_2| object_2| 6| 1|
#| user_2| object_1| 5| 2|
#+-------+---------+-----+----+
一般来说,官方编程指南是开始学习Spark的好地方。
数据
rdd = sc.parallelize([("user_1", "object_1", 3),
("user_1", "object_2", 2),
("user_2", "object_1", 5),
("user_2", "object_2", 2),
("user_2", "object_2", 6)])
df = sqlContext.createDataFrame(rdd, ["user_id", "object_id", "score"])
如果在获得排名相等时使用row_number
而不是rank
,则 Top-n 更准确:
val n = 5
df.select(col('*'), row_number().over(window).alias('row_number'))
.where(col('row_number') <= n)
.limit(20)
.toPandas()
请注意
limit(20).toPandas()
技巧,而不是 Jupyter 笔记本的show()
,以获得更好的格式。
我知道这个问题是pyspark
问的,我正在寻找类似的Scala
答案
在 Scala 中检索数据帧每组中的前 n 个值
这是@mtoto答案的scala
版本。
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions.rank
import org.apache.spark.sql.functions.col
val window = Window.partitionBy("user_id").orderBy('score desc')
val rankByScore = rank().over(window)
df1.select('*, rankByScore as 'rank).filter(col("rank") <= 2).show()
# you can change the value 2 to any number you want. Here 2 represents the top 2 values
更多示例可以在这里找到。
使用 Python 3 和 Spark 2.4
from pyspark.sql import Window
import pyspark.sql.functions as f
def get_topN(df, group_by_columns, order_by_column, n=1):
window_group_by_columns = Window.partitionBy(group_by_columns)
ordered_df = df.select(df.columns + [
f.row_number().over(window_group_by_columns.orderBy(order_by_column.desc())).alias('row_rank')])
topN_df = ordered_df.filter(f"row_rank <= {n}").drop("row_rank")
return topN_df
top_n_df = get_topN(your_dataframe, [group_by_columns],[order_by_columns], 1)
这是另一种没有窗口函数的解决方案,用于从pySpark DataFrame获取前N条记录。
# Import Libraries
from pyspark.sql.functions import col
# Sample Data
rdd = sc.parallelize([("user_1", "object_1", 3),
("user_1", "object_2", 2),
("user_2", "object_1", 5),
("user_2", "object_2", 2),
("user_2", "object_2", 6)])
df = sqlContext.createDataFrame(rdd, ["user_id", "object_id", "score"])
# Get top n records as Row Objects
row_list = df.orderBy(col("score").desc()).head(5)
# Convert row objects to DF
sorted_df = spark.createDataFrame(row_list)
# Display DataFrame
sorted_df.show()
输出
+-------+---------+-----+
|user_id|object_id|score|
+-------+---------+-----+
| user_1| object_2| 2|
| user_2| object_2| 2|
| user_1| object_1| 3|
| user_2| object_1| 5|
| user_2| object_2| 6|
+-------+---------+-----+
如果您对Spark中的更多窗口功能感兴趣,可以参考我的博客之一:https://medium.com/expedia-group-tech/deep-dive-into-apache-spark-window-functions-7b4e39ad3c86
要使用ROW_NUMBER()
函数在 PYSPARK SQLquery 中查找第 N 个最高值:
SELECT * FROM (
SELECT e.*,
ROW_NUMBER() OVER (ORDER BY col_name DESC) rn
FROM Employee e
)
WHERE rn = N
N 是列中所需的第 n 个最高值
输出:
[Stage 2:> (0 + 1) / 1]++++++++++++++++
+-----------+
|col_name |
+-----------+
|1183395 |
+-----------+
查询将返回 N 个最大值