检查列是否具有正确的十进制数 [英] Checking whether a column has proper decimal number
本文介绍了检查列是否具有正确的十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框 (input_dataframe),如下所示:
I have a dataframe (input_dataframe), which looks like as below:
id test_column
1 0.25
2 1.1
3 12
4 test
5 1.3334
6 .11
我想添加一列 result,如果 test_column 具有十进制值,则该列将值设为 1 并且0 如果 test_column 有任何其他值.test_column 的数据类型是字符串.以下是预期的输出:
I want to add a column result, which put values 1 if test_column has a decimal value and 0 if test_column has any other value. data type of test_column is string. Below is the expected output:
id test_column result
1 0.25 1
2 1.1 1
3 12 0
4 test 0
5 1.3334 1
6 .11 1
我们可以使用 pySpark 代码实现它吗?
Can we achieve it using pySpark code?
推荐答案
您可以使用 decimal.Decimal()
这里我们将代码绑定到 UDF 中,然后使用 df.withColumn
Here we are binding the code inside a UDF then using df.withColumn
import decimal
from pyspark.sql.types import IntType
def is_valid_decimal(s):
try:
# return (0 if decimal.Decimal(val) == int(decimal.Decimal(val)) else 1)
return (0 if decimal.Decimal(val)._isinteger() else 1)
except decimal.InvalidOperation:
return 0
# register the UDF for usage
sqlContext.udf.register("is_valid_decimal", is_valid_decimal, IntType())
# Using the UDF
df.withColumn("result", is_valid_decimal("test_column"))
这篇关于检查列是否具有正确的十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文