python-3.x - 是否可以将标量值与 Pandas 系列一起传递给 Pandas UDF 函数
问题描述
我正在尝试scipy.optimize.minimize
对两列 pyspark 数据框使用函数。
在将x0
参数作为数组传递给 Pandas UDF 函数时,我收到以下错误:
TypeError: Invalid argument, not a string or column: [0.9 0.5 2.5 5. 0.33] of type <class 'numpy.ndarray'>. For column literals, use 'lit', 'array', 'struct' or 'create_map' function.
这是我试图最小化的功能
def eb_func(theta, n, e):
"""
# Function to be Minimized
:param theta: float
:param n: Pandas.Series
:param e: Pandas.Series
:return: float
"""
print("Entering EB_Func")
res = res = np.prod(theta[4] * neg_bin(n, e, theta[0], theta[1]) + (1 - theta[4]) * neg_bin(n, e, theta[2], theta[3]))
return res
这是我的 neg_bin 函数:
@pandas_udf('double', PandasUDFType.SCALAR)
def neg_bin(n, e, alpha, beta):
"""
:param n:
:param e:
:param alpha:
:param beta:
:return:
"""
res_expo = gammaln(alpha + n) - gammaln(n + 1) - gammaln(alpha)
res = np.exp(res_expo)
res = res / (1 + beta / (e + 0.01)) ** n
res = res / (1 + e / beta) ** alpha
return res
这些是我的参数:
x0 = np.array([0.9, 0.5, 2.5, 5, 0.33])
bounds = ([0.000001, 200], [0.000001, 200], [0.000001, 200], [0.000001, 200], [0.000001, 1])
这是我试图调用scipy.optimize.minimize
函数的地方。
# Define a function to call minimize function
def RunMinimize(data):
Result = minimize(eb_func, x0, args=(data.Adolescent_a, data.Adolescent_e), method='L-BFGS-B', bounds=bounds, options={'disp': True, 'maxiter': 1000, 'eps': np.repeat(1e-4, 5)})
return Result.x
RunMinimize(df_adol)
我是 PySpark 的新手,我可以在 Pandas 中执行此操作,但现在我有一个庞大的数据集,而 Pandas 需要花费大量时间来处理它。
以下是预期的输出格式:这是我在 Pandas 中得到的输出
[1.00000000e-06, 1.46304225e+00, 1.00000000e-06, 6.39066185e+00, 1.00000000e-06])
我无法将 theta 值传递给 neg_bin 函数。因为 neg_bin 函数只需要 pandas.Series 作为输入。如果可能的话,我正在寻找一种解决方法,将 theta 值作为标量连同 pandas.Series 作为输入发送到 neg_bin 函数。
任何帮助表示赞赏。TIA。
解决方案
推荐阅读
- python - 是否可以在情节中反转子弹图?
- sql - SQL 条件预读
- excel - 使用 ADO 连接在关闭的工作簿中进行多次查找
- android-studio - (Kotlin)如何从另一个活动中的 sharedpreferences 获取数据
- xml - XSLT 检查子字符串是否存在,如果存在则打印
- mysql - Spring JPA @Query 如何连接子表和父表?
- javascript - Blob 不是 Blob - 如何将 canvas.toBlob 存储在 Firestore Blob 中?
- linux - 使用编程命令替换 $() 填充 PATH 环境变量会导致文字巨大的字符串,而不是标记化的路径
- javascript - 如何将参数传递给reactjs中的脚本标签?
- reactjs - Typescript:从文件夹中动态导入一堆 json 文件的最佳方法是什么?