将二进制字符串的列转换为 spark 数据帧中的 int python

Convert column of binary string to int in spark dataframe python

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

+----------+
|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() 可能能够完成这项工作,但我无法弄清楚。有什么想法吗?

我认为 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'))