【发布时间】:2021-08-21 09:34:02
【问题描述】:
我的数据框如下:
------+--------------+
| sid|first_term_gpa|
+------+--------------+
|100170| 2.0|
|100446| 3.8333|
|100884| 2.0|
|101055| 3.0|
|101094| 3.7333|
|101775| 3.7647|
|102524| 3.8235|
|102798| 3.5|
|102960| 2.8235|
|103357| 3.0|
|103747| 3.8571|
|103902| 3.8|
|104053| 3.1667|
|104064| 1.8462|
我已经创建了一个 UDF 函数
def student_gpa(gpa):
bins = ['[0,1)', '[1,2)', '[2,3)', '[3,4)']
return bins[float(gpa)]
参数 gpa 预计为 float
我将上面创建的 UDF 应用到 first_term_gpa 列以创建一个名为 gpa_bin 的新列,代码如下:
alumni_ft_gpa = first_term_gpa \
.withColumn('gpa_bin', expr('student_gpa(first_term_gpa)'))\
.show()
但它会引发错误:
An exception was thrown from a UDF: 'TypeError: list indices must be integers or slices, not float',
我在这里缺少什么?
【问题讨论】:
-
错误很明显——你不能使用浮点数作为列表索引。只需使用 bins[int(gpa)] 代替
-
@mck 我试过了,它抛出了一个异常从 UDF 中抛出:'IndexError: list index out of range'
-
那么你必须检查索引
-
@user1997567:实际上,当我尝试时,这两种解决方案都能完美运行。您能否更新您的问题并尝试我链接到的解决方案之一?
标签: dataframe apache-spark filter pyspark user-defined-functions