如何在scala spark中添加具有指定位数的前导零填充?
我有如下如何在scala spark中添加具有指定位数的前导零填充?,scala,apache-spark-sql,Scala,Apache Spark Sql,我有如下data.txt文件 12, 345, 6789 现在,我想在参数文件或标准输入的指定字段中使用指定的位数执行前导零填充。 在参数文件的指定字段中指定的位数为8位。 我该怎么办 这是我的代码: import org.apache.spark.sql.types._ import org.apache.spark.sql.types._ import org.apache.spark.SparkConf import org.apache.spark.SparkContext imp
data.txt
文件
12, 345, 6789
现在,我想在参数文件或标准输入的指定字段中使用指定的位数执行前导零填充。
在参数文件的指定字段中指定的位数为8位。
我该怎么办
这是我的代码:
import org.apache.spark.sql.types._
import org.apache.spark.sql.types._
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.sql._
//Convert textfile to DF
val conf = new SparkConf().setAppName("ct").setMaster("local").set("spark.driver.allowMultipleContexts", "true")
val sc = SparkContext(conf)
val sparkSess = SparkSession.builder().appName("SparkSessionZipsExample").config(conf).getOrCreate()
val path = "data.txt"
val data = sc.textFile(path)
val colNum = data.first().split(",").size
var schemaString = "key"
for( i <- 1 to colNum - 1) {
schemaString += " value" + i
}
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable=true))
val schema = StructType(fields)
val dfWithSchema = sparkSess.read.option("header", "false").schema(schema).csv(path)
dfWithSchema.show()
//add leading zero padding with the specified number of digits
//The number of digits specified in the specified field of the argument file is 8 digits
val df = dfWithSchema.withColumn("key", format_string("%08d", $"key")).show
val df2 = dfWithSchema.withColumn("value2", format_string("%08d", $"value2")).show
您可以使用内置的
lpad
函数,如下所示:
import org.apache.spark.sql.functions.lpad
dfWithSchema.select(
lpad($"key", 8, "0",
lpad($"value2", 8, "0"),
$"value1"
).show
这将在字符串前面插入0,最多8个字符
有关详细信息,请参阅。Hi@Alexandros Biratsist此结果输出缺少列
value1
的值?请更新代码帮助我。您好,John value1没有更改。您可以像我上面所做的那样将其包含在select语句中,请检查修改后的版本Hi@Alexandros Biratsisthis,非常感谢。好办法!
import org.apache.spark.sql.functions.lpad
dfWithSchema.select(
lpad($"key", 8, "0",
lpad($"value2", 8, "0"),
$"value1"
).show