在 Pandas 中对 Window PartitionBy 进行排名

我接触了一些需要在面向 Pandas 的处理中进行翻译的 PySpark 代码。任何帮助都会非常受欢迎,因为我正在努力寻找 Pandas 等价物的方法:


PySpark代码:


window = Window.partitionBy(df["timestamp"]).orderBy(df["timestamp"].desc())


df = df.select('*', F.rank().over(window).alias('rank')) \

       .filter(F.col('rank') <= 1) \

       .orderBy(df["timestamp"].desc()) \

       .limit(int(window_int))

谢谢


慕桂英3389331
浏览 65回答 1
1回答

ABOUTYOU

您可以使用sqldffrompandasql来实现简单的sql类似窗口的体验。该库实际上使用sqlite支持窗口函数的语法,每个变量/数据帧都可以被视为一个表。该函数sqldf还返回一个DataFramefrom pandasql import sqldfdf = sqldf("""&nbsp;SELECT * FROM (&nbsp; &nbsp; &nbsp;SELECT&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; * ,&nbsp; &nbsp; &nbsp; &nbsp; RANK() OVER (PARTITION BY timestamp ORDER&nbsp; BY timestamp ) as rank&nbsp; &nbsp; &nbsp;FROM&nbsp; &nbsp; &nbsp; &nbsp; df&nbsp; &nbsp; &nbsp;ORDER BY timestamp desc&nbsp;) dfsub&nbsp;WHERE&nbsp; &nbsp; rank <= 1&nbsp;LIMIT %d""" % (int(window_int)))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python