PySpark:使用过滤功能后取一列的平均值 [英] PySpark: Take average of a column after using filter function
本文介绍了PySpark:使用过滤功能后取一列的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码来获取工资高于某个阈值的人的平均年龄.
I am using the following code to get the average age of people whose salary is greater than some threshold.
dataframe.filter(df['salary'] > 100000).agg({"avg": "age"})
列年龄是数字(浮点数)但我仍然收到此错误.
the column age is numeric (float) but still I am getting this error.
py4j.protocol.Py4JJavaError: An error occurred while calling o86.agg.
: scala.MatchError: age (of class java.lang.String)
你知道不使用groupBy
函数和SQL查询的任何其他方法来获得平均值等.
Do you know any other way to obtain the avg etc. without using groupBy
function and SQL queries.
推荐答案
聚合函数应该是一个值和一个列名一个键:
Aggregation function should be a value and a column name a key:
dataframe.filter(df['salary'] > 100000).agg({"age": "avg"})
或者你可以使用pyspark.sql.functions
:
from pyspark.sql.functions import col, avg
dataframe.filter(df['salary'] > 100000).agg(avg(col("age")))
也可以使用 CASE .. WHEN
from pyspark.sql.functions import when
dataframe.select(avg(when(df['salary'] > 100000, df['age'])))
这篇关于PySpark:使用过滤功能后取一列的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文