pyspark常用功能记录

前言

pyspark中很多常用的功能,过段时间没有使用就容易忘记,需要去网上搜索,这里总结一下,省的以后还去去搜,供自己以后参考。

withColumn

python 复制代码
def hot_func(info_str):
    if info_str:
         eturn "1"
    return "0"
df = df.withColumn("is_hot", F.udf(hot_func, StringType())(F.col("your_col_name")))

自定义函数

python 复制代码
from pyspark.sql.functions import udf  
# 定义并注册函数
@udf(returnType=StringType())
def f_parse_category(info):
    x = json.loads(info)['category']
    return x if x is not None else ''
spark.udf.register('f_parse_category', f_parse_category)
# 在sql中使用注册的函数
sql = """
select *, f_parse_category(info) category, 
from your_table
where info is not null 
"""
df = spark.sql(sql).cache()

groupby处理

按groupby处理,保留goupby字段,并对groupby的结果处理。正常情况下,使用df.groupBy即可,但需要处理多列并逻辑较为复杂时,可以使用这种方式。

python 复制代码
from pyspark.sql.functions import pandas_udf                                                         
from pyspark.sql.functions import PandasUDFType 
from pyspark.sql.types import StructField, LongType, StringType, StructType
from collections import Counter

pattern = re.compile(r'\b\w+(?:' + '|'.join(['_size', '_sum']) + r')\b')

group_cols = ['category']
value_cols = ['sales_sum', 'stat_size']

schema = StructType(                                                                                
                    [StructField(col, LongType()) if len(re.findall(pattern, col))>0 else StructField(col, StringType())  for col in group_cols+value_cols],
                    )

@pandas_udf(schema, functionType=PandasUDFType.GROUPED_MAP)                                          
def group_stat(df):
	# 获取
    l = [df[item].iloc[0] for item in group_cols]
    df = df[[col for col in df.columns if col not in group_cols]]
    sales_sum = df['sales'].sum().item()
    stat_size = len(df)
    
    # d: {"key": "value"}
    df['first_attr'] = df['attr'].transform(lambda d: list(json.loads(d).keys())[0])
    attr_dict = json.dumps({k:v for k, v in Counter(df['first_attr'].value_counts().to_dict()).most_common()}, ensure_ascii=0)
   
    counter = sum(df['brand_name'].apply(lambda x:Counter(json.loads(x))), Counter())
    ct = len(counter)
    brand_list = df["brand"].to_list()
    values = [sales_sum, stat_size, attr_dict, ct, infobox_brand_stat, brand_list]
    return pd.DataFrame([l + values])

# df 包含字段:category, sales, attr, brand_name, brand
df = df.groupby(group_cols).apply(group_stat).cache()

patition By & orderBy

python 复制代码
from pyspark.sql.window import Window
from pyspark.sql.functions import row_number, dense_rank
# 根据department分区,然后按salary排序编号
windowSpec  = Window.partitionBy("department").orderBy("salary")
df.withColumn("row_number",row_number().over(windowSpec)) \
    .show(truncate=False)
# dense_rank: 相同值排序编号一致

sql的方式:

python 复制代码
select 
	name, category, sales, 
	DENSE_RANK() OVER (PARTITION BY category ORDER BY b.sales DESC) as sales_rank
from your_tb

dataframe转正rdd处理行

该中情况一般在需要处理过个行的情况下使用,如果是少数的行处理,可以使用withColumn

python 复制代码
def hot_func(info_str):
    if info_str:
         eturn "1"
    return "0"
df = df.withColumn("is_hot", F.udf(hot_func, StringType())(F.col("your_col_name")))
转为rdd的处理方式为:
python 复制代码
def gen_norm(row):
	# 转为字段处理
    row_dict = row.asDict(recursive=True)
    process_key = row_dict["key"]
    row_dict["process_key"] = process_key
    return Row(**row_dict)
# sampleRatio=0.01 为推断列类型的抽样数据比例
df = df.rdd.map(gen_norm).toDF(sampleRatio=0.01).cache()
df.show()
相关推荐
qq5918406852 小时前
uiautomator2自动化安卓手机操作
python
80s7772 小时前
动态代理和静态代理的区别,动态代理怎么提高网络安全性
python
niucloud-admin4 小时前
JAVA V6 多商户商城 开发文档——job 计划任务开发
java·python·github
小叶肥辉4 小时前
LangChain链和LangGraph图的学习笔记【三】——分别用langchain_openai库和langchain_community库调用大模型
笔记·python·langchain
2401_873479405 小时前
IP属地为什么有时显示外省?用IP查询工具核查动态分配、运营商出口与GeoIP库
python·tcp/ip·ip
OKkankan7 小时前
LangChain 能力详解!:输出解析、RAG、向量数据库与 Retriever 检索器
数据结构·python·langchain·ai应用
山哥ol7 小时前
【Geany 环境配置与中文乱码解决参考】
python
会飞锦鲤8 小时前
基于 Mask R-CNN 的药片缺陷检测系统
人工智能·pytorch·python·神经网络·resnet-50
默 语8 小时前
Java新手入门:从零开始安装JDK并配置环境变量
java·开发语言·python·mysql·group by·1024程序员节·数据去重
清水白石0088 小时前
Python 异步编程深度解析:Cancellation 到底是异常还是控制信号?从 asyncio 取消机制到企业级事务设计最佳实践
开发语言·python