PySpark:使用过滤器功能后取一列的平均值 [英] PySpark: Take average of a column after using filter function

查看:126
本文介绍了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查询获取avg等的任何其他方法.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆