【问题标题】:getting nulls when concatenating string columns in pyspark. Why?在 pyspark 中连接字符串列时得到空值。为什么?
【发布时间】:2020-04-26 13:23:12
【问题描述】:

我有这个超级简单的数据框:

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)

我想添加一个新列,它只是“案例编号”列和“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

为什么会这样?谢谢!

【问题讨论】:

  • 我不知道pyspark,但也许应该是rc1.col("Case number")
  • Pyspark 不会使用 + 运算符连接字符串。使用concat

标签: python string dataframe apache-spark pyspark


【解决方案1】:

好的,伙计们,这很好用:

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|
+--------+-----------+-------------+

但是,我不能完全弄清楚为什么这是 null:

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

不过没关系

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 2014-11-23
    • 2021-10-29
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多