python - 在火花数据框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() 可能能够完成这项工作,但我无法弄清楚。有任何想法吗?
解决方案
我认为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'))
推荐阅读
- java - Java:克隆字符串生成器的内容并将项目附加到每一行
- .htaccess - 在 .htacess 中设置 Expires Header 对于 Woocommerce 网站来说是一个糟糕的主意吗?
- ms-access - 我在 MS Access 的对象概览中看不到表格
- c++ - 负载测试 rpc 应用程序
- python-3.x - 从两个 .txt 文件中打印特定名称
- asp.net - 防止在 ASP.Net Web 窗体中从外部源触发电子邮件
- git - 如何从python脚本接收返回值到预提交钩子
- android - 每个 RecyclerView.ViewHolder 一个 ViewModel 或(等效)
- excel - 根据 2 个标准输入将行从一个 Excel 工作表复制到另一个工作表
- php - 作曲家。如何根据用户 php 版本安装特定版本的包?