在pyspark中连接字符串列时获取空值。为什么?

2024-06-16 12:42:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个超级简单的数据帧:

rc1.show(5)
rc1.printSchema()
+--------+-----------+
|      ID|Case number|
+--------+-----------+
|11034701|   JA366925|
|11227287|   JB147188|
|11227583|   JB147595|
|11227293|   JB147230|
|11227634|   JB147599|
+--------+-----------+
only showing top 5 rows

root
 |-- ID: string (nullable = true)
 |-- Case number: string (nullable = true)

我想添加一个新的列,它只是“Case number”列和“aaa”列的串联,所以我用这个来实现:

rc2 = rc1.withColumn("Case numberxx", col("Case number") + "aaa")
rc2.show(5)

然而,就我的一生而言,我无法理解为什么我的新专栏充满了空值:

+--------+-----------+-------------+
|      ID|Case number|Case numberxx|
+--------+-----------+-------------+
|11034701|   JA366925|         null|
|11227287|   JB147188|         null|
|11227583|   JB147595|         null|
|11227293|   JB147230|         null|
|11227634|   JB147599|         null|
+--------+-----------+-------------+
only showing top 5 rows

为什么会这样?谢谢


Tags: idnumberonlytoprc1shownullrows
1条回答
网友
1楼 · 发布于 2024-06-16 12:42:12

好了,伙计们,这很有效:

from pyspark.sql.functions import concat, lit

rc2 = rc1.withColumn("Case numberxx", concat(col("Case number"), lit("aaa")))
rc2.show(5)

+    +     -+      -+
|      ID|Case number|Case numberxx|
+    +     -+      -+
|11034701|   JA366925|  JA366925aaa|
|11227287|   JB147188|  JB147188aaa|
|11227583|   JB147595|  JB147595aaa|
|11227293|   JB147230|  JB147230aaa|
|11227634|   JB147599|  JB147599aaa|
+    +     -+      -+

但是,我不太明白为什么这是空的:

col("Case number") + lit("aaa")

但这没关系

concat(col("Case number"), lit("aaa"))

相关问题 更多 >