pyspark统计指标计算

下面介绍如何使用pyspark处理计算超大数据的统计指标,主要为:最大值、最小值、均值、方差、标准差、中位数、众数、非重复值等。

python 复制代码
# 加载稽核数据
rd_sql = f"select * from database.table"
spark_data = spark.sql(rd_sql)
python 复制代码
# 计算众数 由于spark 2.4版本未内置相关函数 需要自定义
import pyspark.sql.functions as F
# 自定义mode的计算
def sparkdf_mode(df, cols):
    # 构建一个空数据框
    mode_df = pd.DataFrame()
    # 循环每一列
    for col in cols:
        # 先过滤空值
        filtered_df = df.filter(F.col(col).isNotNull())
        # 加个判断 防止数据全空置时报错
        if filtered_df.count()>0:
            # 统计出现次数 排序
            grouped_counts = filtered_df.groupBy(col).count().orderBy(F.col("count").desc())
            # 获取计数值最大的第一行
            first_row = grouped_counts.first()
            # 转sparkdf
            pdf = spark.createDataFrame([first_row], grouped_counts.columns).toPandas()[col]
        else:
            # 数据全空置 赋值None
            pdf = pd.DataFrame({col: [None]}) 
        # 拼接
        mode_df = pd.concat([mode_df, pdf], axis=1)
    return mode_df
python 复制代码
from pyspark.sql.functions import col, count, when, approx_count_distinct
# 分开统计 先统计字符类型
# 统计指标
string_stats = spark_data.select(string_cols+date_cols).summary("max","min").toPandas()
# 非空值数量
string_nonull = spark_data.select([count(when(col(c).isNotNull(), c)).alias(c) for c in (string_cols+date_cols)]).toPandas()
# 非重复值
string_unique = spark_data.agg(*[approx_count_distinct(col(c)).alias(c) for c in (string_cols+date_cols)]).toPandas()
# 众数
string_mode = sparkdf_mode(spark_data, (string_cols+date_cols))
# 添加空值占位
null_rows = pd.DataFrame(None, index=np.arange(len(string_stats), len(string_stats) + 3), columns=string_stats.columns)
string_stats = string_stats.append(null_rows)
# 上下拼接
string_data = pd.concat([string_stats.iloc[:, 1:], string_nonull, string_unique, string_mode])
print(f"string_data稽核完成")
python 复制代码
# 统计数值类型
# 统计指标
float_stats = spark_data.select(float_cols).summary("max","min","mean","50%","stddev").toPandas()
print(f"float_stats稽核完成")
# 非空值
float_nonull = spark_data.select([count(when(col(c).isNotNull(), c)).alias(c) for c in float_cols]).toPandas()
# 非重复值
float_unique = spark_data.agg(*[approx_count_distinct(col(c)).alias(c) for c in float_cols]).toPandas()
# 众数
float_mode = sparkdf_mode(spark_data, float_cols)
# 上下拼接
float_data = pd.concat([float_stats.iloc[:, 1:], float_nonull, float_unique, float_mode])
print(f"float_data稽核完成")
python 复制代码
# 合并转置
pdf = pd.concat([string_data, float_data], axis=1).T
# 重命名
pdf.columns = ["max", "min", "mean", "median", "std", "nonull_cnt", "unique_cnt", "mode"]
# pdf转为sdf
sdf = spark.createDataFrame(pdf)
# 创建临时视图 用于sqlAPI操作
sdf.createOrReplaceTempView("temp_view")
# 插入库表
spark.sql(f"insert overwrite table database.table select * from temp_view")
# 用完删除临时视图
spark.catalog.dropTempView("temp_view")
# 关闭spark
spark.stop()
相关推荐
ZWZhangYu2 分钟前
LangChain 构建向量数据库和检索器
数据库·langchain·easyui
Python×CATIA工业智造3 分钟前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco33 分钟前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
feifeigo1231 小时前
升级到MySQL 8.4,MySQL启动报错:io_setup() failed with EAGAIN
数据库·mysql·adb
狐凄1 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
悦悦子a啊2 小时前
Python之--基本知识
开发语言·前端·python
火龙谷3 小时前
【nosql】有哪些非关系型数据库?
数据库·nosql
焱焱枫3 小时前
Oracle获取执行计划之10046 技术详解
数据库·oracle
Bug退退退1234 小时前
RabbitMQ 高级特性之死信队列
java·分布式·spring·rabbitmq
笑稀了的野生俊4 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力