PySpark - 如何根据条件将 0 的字符串前缀连接到另一个字符串列

PySpark - How can I concatenate a string prefix of 0's to another string column based on a condition

我有一个 DataFrame,如下所示

|string_code|prefix_string_code|
|1234       |001234            |
|123        |000123            |
|56789      |056789            |

基本上我想要的是根据需要添加尽可能多的“0”,以便列 prefix_string_code 的长度为 6

我尝试过的:

df.withColumn('prefix_string_code', when(length(col('string_code')) < 6, concat(lit('0' * (6 - length(col('string_code')))), col('string_code'))).otherwise(col('string_code')))

它没有工作,而是产生了以下内容:

|string_code|prefix_string_code|
|1234       |0.001234          |
|123        |0.000123          |
|56789      |0.056789          |

如您所见,如果它不是十进制形式,则代码确实有效。我该如何正确执行此操作?

谢谢!

这种情况你可以使用 lpad 功能

>>> import pyspark.sql.functions as F

>>> rdd = sc.parallelize([1234,123,56789,1234567])
>>> data = rdd.map(lambda x: Row(x))
>>> df=spark.createDataFrame(data,['string_code'])
>>> df.show()
+-----------+
|string_code|
+-----------+
|       1234|
|        123|
|      56789|
|    1234567|
+-----------+

>>> df.withColumn('prefix_string_code', F.when(F.length(df['string_code']) < 6 ,F.lpad(df['string_code'],6,'0')).otherwise(df['string_code'])).show()
+-----------+------------------+
|string_code|prefix_string_code|
+-----------+------------------+
|       1234|            001234|
|        123|            000123|
|      56789|            056789|
|    1234567|           1234567|
+-----------+------------------+