我有一个带有多列的df,其中一列在arraytype中,名为“requests”,其中包含两个字段“id”和“responses”:
(requests,ArrayType(StructType(StructField(id,IntegerType,true),StructField(responses,ArrayType(IntegerType,false),true))))
从一个“requests”数组中,我想得到一个“id”与特定值匹配的请求,并将其添加到一个新列中。
到目前为止,我添加了一个布尔值来表示该值是否存在于列表中:
dF
.withColumn("idPresent", array_contains(col("requests.id"), 55))
.show()
但当我把“id”作为参数时,我不知道怎样才能得到一个请求类型的对象?我希望数组中只存在一个这样的对象,但是如果不止一个,第一个就足够了。我想将新的匹配对象添加到新列中。
2条答案
按热度按时间gcxthw6b1#
扩展@leo c的答案,您还可以使用
filter
要根据数组元素的id筛选它们,请执行以下操作:如果只需要第一个struct对象,可以添加
[0]
到expr
:3gtaxfhh2#
考虑使用高阶函数
transform
取消与“id”不匹配的请求,然后用array_except
: