#博学谷IT学习技术支持#
pyspark 在跑自定义UDAF函数时遇到的一个问题
问题场景:
在SparkSQL中,因为需要用到自定义的UDAF函数,所以用pyspark自定义了一个,但是遇到了一个问题,就是自定义的UDAF函数一直报
AttributeError: 'NoneType' object has no attribute '_jvm'
在此将解决过程记录下来
问题描述
在新建的py文件中,先自定义了一个UDAF函数,然后在 if __name__ == '__main__':
中调用,死活跑不起来,一遍又一遍的对源码,看起来自定义的函数也没错:过程如下:
import decimal
import os
import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
os.environ['SPARK_HOME'] = '/export/server/spark'
os.environ["PYSPARK_PYTHON"] = "/root/anaconda3/bin/python"
os.environ["PYSPARK_DRIVER_PYTHON"] = "/root/anaconda3/bin/python"
@F.pandas_udf('decimal(17,12)')
def udaf_lx(qx: pd.Series, lx: pd.Series) -> decimal:
# 初始值 也一定是decimal类型
tmp_qx = decimal.Decimal(0)
tmp_lx = decimal.Decimal(0)
for index in range(0, qx.size):
if index == 0:
tmp_qx = decimal.Decimal(qx[index])
tmp_lx = decimal.Decimal(lx[index])
else:
# 计算lx: 计算后,保证数据小数位为12位,与返回类型的设置小数位保持一致
tmp_lx = (tmp_lx