0

我有一个在两个数据帧上执行连接的简单用例,我使用的是 spark 1.6.3 版本。问题是,在尝试使用 cast 方法将字符串类型转换为整数类型时,结果列都是空值。

我已经尝试过这里提到的所有解决方案How to cast a column in dataframe? 但是所有问题都有scala api的答案,我找不到任何使用java api的人。

DataFrame dataFromDB = getDataFromDB("(select * from schema.table where 
col1 is not null)"); //This method uses spark sql 
                    //to connect to a db2 data base and get the data

//I perform the cast operation as
dataFromDB.withColumn("INCOME_DATA", dataFromDB.col("INCOME_DATA")
                                    .cast(DataTypes.IntegerType));
//but the above results in null values
//other things I tried based on the link above is below
dataFromDB.selectExpr(cast("INCOME_DATA" as integer")) //this too produces null values

//I tried to remove the whitespaces from income data column with no success
dataFromDB.select(dataFromDB.col("INCOME_DATA").toString().replaceAll("\\s+", ""); //this does not remove any whitespace

我无法找到它的解决方案,而且我尝试转换的列是字符串类型并且可能包含尾随空格,这可能是一个问题吗?如果是,那么我该如何删除它们,我尝试如下删除它们,但似乎不起作用。这是我第一次使用 spark 数据框,因此非常感谢任何帮助。谢谢!

4

1 回答 1

0

你可以为你的最后一行尝试这样的事情吗?

import org.apache.spark.sql.functions._
dataFromDB.withColumn("INCOME_DATA", regexp_replace($"INCOME_DATA", "\\s+", "")).select("INCOME_DATA")

在 Java 中:

dataFromDB.withColumn("INCOME_DATA", functions.regexp_replace(functions.col("INCOME_DATA"), "\\s+", "")).select("INCOME_DATA");
于 2018-12-19T22:07:18.457 回答