提问人:Arturo Sbr 提问时间:6/3/2023 更新时间:6/3/2023 访问量:127
PySpark:将 null 值替换为空列表
PySpark: Replace null values with empty list
问:
我外部连接了两个和操作的结果,并最终得到了这个数据帧():groupBy
collect_set
foo
>>> foo.show(3)
+---+------+------+
| id| c1| c2|
+---+------+------+
| 0| null| [1]|
| 7| [6]| null|
| 6| [6]|[7, 8]|
+---+------+------+
我想连接并一起得到这个结果:c1
c2
+---+------+------+---------+
| id| c1| c2| res|
+---+------+------+---------+
| 0| null| [1]| [1]|
| 7| [6]| null| [6]|
| 6| [6]|[7, 8]|[6, 7, 8]|
+---+------+------+---------+
为此,我需要将 和 中的 null 值合并在一起。但是,我什至不知道数据类型和是什么。如何用 和 的串联替换 null 值,如上所示?c1
c2
c1
c2
[]
c1
c2
res
这就是我目前连接两个列的方式:
# Concat returns null for rows where either column is null
foo.selectExpr(
'id',
'c1',
'c2',
'concat(c1, c2) as res'
)
答:
1赞
C.Nivs
6/3/2023
#1
您想使用:fillna
from pyspark.sql import functions as F
# Fill null values with empty list
foo = foo.fillna(F.lit([]), subset=['c1', 'c2'])
# now you can use your selectExpr
foo.selectExpr(
'id',
'c1',
'c2',
'concat(c1, c2) as res'
)
评论
0赞
Arturo Sbr
6/3/2023
谢谢!可悲的是,我收到一个丑陋的错误:> Py4JJavaError:调用 z:org.apache.spark.sql.functions.lit 时出错。:java.lang.RuntimeException:不支持的文本类型类 java.util.ArrayList []
2赞
notNull
6/3/2023
#2
在这种情况下,请尝试使用 array_except,array_union
个函数。
Example:
from pyspark.sql.functions import *
df = spark.createDataFrame([(0,[None],[1]),(7,[6],[None]),(6,[6],[7,8])],['id','c1','c2'])
df.withColumn("res",expr("""array_except(array_union(c1,c2),array(null))""")).show()
#+---+------+------+---------+
#| id| c1| c2| res|
#+---+------+------+---------+
#| 0|[null]| [1]| [1]|
#| 7| [6]|[null]| [6]|
#| 6| [6]|[7, 8]|[6, 7, 8]|
#+---+------+------+---------+
评论