首页 > 解决方案 > 在火花数据框python中将二进制字符串的列转换为int

问题描述

所以我有一个数据框,其中有一列是这样的:

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

标签: pythonpysparkapache-spark-sqlpyspark-dataframes

解决方案


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

推荐阅读