【问题标题】:Change array value pyspark更改数组值pyspark
【发布时间】:2020-02-24 12:20:15
【问题描述】:

我有一个 pyspark 数据框:

例子df:

number  |  matricule<array>   | name<array>  |    
----------------------------------------------
AA      |  []                 |  [7]         |    
----------------------------------------------
AA      |  [9]                |  []         |     
----------------------------------------------
AA      |  [""]                |  [2]         |    
----------------------------------------------
AA      |  [2]                |  [""]      |  

当数组的值为string but is empty: [""] to [] 时,我想更改它们 我试过了:

df = df.withColumn("matricule_2", F.when(F.col("matricule") == F.lit("[""]"), F.lit("[]")).otherwise(F.col("matricule")))

但我得到了一个错误:

AnalysisException: u"cannot resolve, `matricule` = '[]')' due to data type mismatch: differing types.

预期结果:

number  |  matricule<array>   | name<array>  |    
----------------------------------------------
AA      |  []                 |  [7]         |    
----------------------------------------------
AA      |  [9]                |  []          |     
----------------------------------------------
AA      |  []                |  [2]          |    
----------------------------------------------
AA      |  [2]                |  []          |  

请有人可以帮助我吗? 谢谢

【问题讨论】:

  • 您要将空字符串转换为空值还是将其从数组中完全删除?
  • @blackbishop 删除它们并保留一个空数组 []
  • 如果您使用的是 Spark 2.4+,您可以像这样使用array_removedf = df.withColumn("matricule_2", array_remove(col("matricule"), ""))...

标签: pyspark


【解决方案1】:

数据框:

+------+---------+----+
|Number|Matricule|Name|
+------+---------+----+
|    AA|     [""]| [7]|
|    AA|      [9]|  []|
|    AA|     [""]| [2]|
|    AA|      [2]|[""]|
+------+---------+----+

过滤掉两列中的“”:

df.withColumn("Matricule", F.expr("""filter(Matricule, x -> x!= '""')"""))\
  .withColumn("Name", F.expr("""filter(Name, x -> x!= '""')""")).show()


+------+---------+----+
|Number|Matricule|Name|
+------+---------+----+
|    AA|       []| [7]|
|    AA|      [9]|  []|
|    AA|       []| [2]|
|    AA|      [2]|  []|
+------+---------+----+

如 cmets 中所述,您还可以使用 array_remove:

df.withColumn("Matricule", F.array_remove("Matricule", '""'))\
  .withColumn("Name", F.array_remove("Name", '""')).show()

+------+---------+----+
|Number|Matricule|Name|
+------+---------+----+
|    AA|       []| [7]|
|    AA|      [9]|  []|
|    AA|       []| [2]|
|    AA|      [2]|  []|
+------+---------+----+

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多