在 Spark DataFrame python 中将二进制字符串的列转换为 int

问题描述 投票:0回答:2

所以我有一个包含这样一列的数据框:

+----------+
|some_colum|
+----------+
|        10|
|        00|
|        00|
|        10|
|        10|
|        00|
|        10|
|        00|
|        00|
|        10|
+----------+

其中 some_colum 列是二进制字符串。

我想将此列转换为十进制。

我尝试过做

data = data.withColumn("some_colum", int(col("some_colum"), 2))

但这似乎不起作用。当我收到错误时:

int() can't convert non-string with explicit base

我认为cast()可能能够完成这项工作,但我无法弄清楚。有什么想法吗?

python apache-spark-sql pyspark
2个回答
2
投票

我认为

int
不能直接应用于列。您可以在 udf 中使用:

from org.apache.spark.sql import functions
binary_to_int = functions.udf(lambda x: int(x, 2), IntegerType())
data = data.withColumn("some_colum", binary_to_int("some_colum").alias('some_column_int'))

0
投票
def to_decimal(input_column, base_value):
    return int(input_column, base_value)  

to_decimal_udf = udf(to_decimal, IntegerType())
df = df.withColumn("decimal_value_binary",\
to_decimal_udf(col("binary_sensor_data"),\
lit(2)))

df.show()
© www.soinside.com 2019 - 2024. All rights reserved.