【问题标题】:pyspark - attempting to create new column based on the difference of two ArrayType columnspyspark - 尝试根据两个 ArrayType 列的差异创建新列
【发布时间】:2017-10-17 21:15:23
【问题描述】:

我有一张这样的桌子:

+-----+----+-------+-------+
|name | id | msg_a | msg_b |
+-----+----+-------+-------+
|    a|   3|[a,b,c]|[c]    |
|    b|   5|[x,y,z]|[h,x,z]|
|    c|   7|[a,x,y]|[j,x,y]|
+-----+----+-------+-------+

我想添加一个列,以便显示 msg_b 中但不是 msg_a 中的任何内容。 例如

+-----+----+-------+-------+------------+
|name | id | msg_a | msg_b | difference |
+-----+----+-------+-------+------------+
|    a|   3|[a,b,c]|[c]    |NA          |
|    b|   5|[x,y,z]|[h,x,z]|[h]         |
|    c|   7|[a,x,y]|[j,x,y]|[j]         |
+-----+----+-------+-------+------------+

参考previous post,我试过了 df.select('msg_b').subtract(df.select('msg_a')).show() 可行,但我需要将信息作为表格,nameid

这样做: df.withColumn("difference", F.col('msg_b').subtract(F.col(''msg_a'))).show(5) 产生一个TypeError: 'Column' object is not callable

不确定是否有单独的函数来执行此操作,如果我遗漏了一些明显的东西,等等。

【问题讨论】:

    标签: apache-spark pyspark spark-dataframe


    【解决方案1】:

    你必须使用UDF:

    from pyspark.sql.functions import *
    from pyspark.sql.types import *
    
    @udf(ArrayType(StringType()))
    def subtract(xs, ys):
        return list(set(xs) - set(ys))
    

    例子

    df = sc.parallelize([
       (["a", "b", "c"], ["c"]), (["x", "y", "z"], ["h", "x", "z"])
    ]).toDF(["msg_a", "msg_b"])
    
    df.select(subtract('msg_b', 'msg_a'))
    
    +----------------------+
    |subtract(msg_b, msg_a)|
    +----------------------+
    |                    []|
    |                   [h]|
    +----------------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 2020-11-19
      • 2023-03-27
      • 2017-04-30
      • 2019-05-17
      • 1970-01-01
      相关资源
      最近更新 更多