2

我有一个 pyspark 数据框:

number  |  matricule      
--------------------------------------------
1       |  ["AZ 1234", "1234", "00100"]                   
--------------------------------------------
23      |  ["1010", "12987"]                   
--------------------------------------------
56      |  ["AZ 98989", "22222", "98989"]                   
--------------------------------------------

matricule数组中,如果我删除AZ字符串,我会有重复的值。我想删除字符串然后删除 数组"AZ"中的重复值。matricule知道有时我后面有一个空格AZ,我也应该删除它。

我做了一个udf:

def remove_AZ(A)
    for item in A:
        if item.startswith('AZ'):
            item.replace('AZ','')
udf_remove_AZ = F.udf(remove_AZ)
df = df.withColumn("AZ_2", udf_remove_AZ(df.matricule))

我在所有AZ_2列中都为空。

如何从matricule数组中的每个值中删除 AZ,然后删除里面的重复项?谢谢

4

2 回答 2

6

对于 Spark 2.4+,您可以像这样使用transform+array_distinct函数:

t = "transform(matricule, x -> trim(regexp_replace(x, '^AZ', '')))"
df.withColumn("matricule", array_distinct(expr(t))).show(truncate=False) 

#+------+--------------+
#|number|matricule     |
#+------+--------------+
#|1     |[1234, 00100] |
#|23    |[1010, 12987] |
#|56    |[98989, 22222]|
#+------+--------------+

对于数组的每个元素 using transform,我们AZ从字符串的开头删除字符 usingregexp_replace以及trim前导和尾随空格(如果有)。

于 2020-02-26T12:53:03.117 回答
3

你能把你的udf写成:

def remove_az(array):
    array = [w.replace('AZ', '').strip() for w in array]
    return array

remove_az_udf = F.udf(remove_az)

df = df.withColumn("AZ_2", remove_az_udf(df.matricule))
于 2020-02-26T12:52:46.680 回答