Sql 将最后50行传递给spark数据帧pyspark中的udf
作为一个简化的示例,我有一个数据帧:Sql 将最后50行传递给spark数据帧pyspark中的udf,sql,apache-spark-sql,spark-dataframe,window-functions,pyspark-sql,Sql,Apache Spark Sql,Spark Dataframe,Window Functions,Pyspark Sql,作为一个简化的示例,我有一个数据帧: name index x y speed a 1 12.5 14 1,0 a 2 13 14.5 2.2 a 3 13.5 15 3.2 a 4 14 15.5 4.5 a 5 14.5 16 5.6 a 6 15 16.5 7.5 a
name index x y speed
a 1 12.5 14 1,0
a 2 13 14.5 2.2
a 3 13.5 15 3.2
a 4 14 15.5 4.5
a 5 14.5 16 5.6
a 6 15 16.5 7.5
a 7 15.5 17 6.5
b 1 17.5 19 5.5
b 2 18 19.5 6.6
和一个UDF函数,如下所示:
def dis_calc(cur_idx, *speed_series):
dis=0
for i in range(len(speed_series)):
dis += speed_series[i] * 0.1
if dis > 5:
return cur_idx + i
总之,我只想找到每行5米内的邻居,并保存邻居的索引。为此,我必须将最后大约50行的速度传递给UDF:dis_calc。
我能做的只是:
w = Window.partitionBy("name").orderBy("index")
udffun = udf(dis_calc)
test_df = test_df.withColumn("neighbor_index", udffun(col("index"), ???))
我怎样才能填补“?”这个位置
我不是个好主意:
我可以将整个命令组合成一个字符串,并使用eval执行它
str_command = "test_df.withColumn("neighbor_index", udffun(col("index"), "
for i in range(50):
str_command += "lag(col("speed"),{}).over(w),".format(i)
str_command = str_command[:-1] + "))"
test_df = eval(str_command)
然而,我知道这绝对是个坏主意,因为有时我可能需要超过最后50行,也许100行
有人有更好的方法来解决这个问题吗