【问题标题】:Pyspark Dataframe get unique elements from column with string as list of elementsPyspark Dataframe 从具有字符串的列中获取唯一元素作为元素列表
【发布时间】:2018-05-27 08:46:49
【问题描述】:

我有一个数据框(通过从 azure 中的多个 blob 加载创建),其中有一列是 ID 列表。 现在,我想要整个列中的唯一 ID 列表:

这是一个例子 -

df - 
| col1 | col2 | col3  |
| "a"  | "b"  |"[q,r]"|
| "c"  | "f"  |"[s,r]"|

这是我预期的回应:

resp = [q, r, s]

知道怎么去那里吗?

我目前的方法是将 col3 中的字符串转换为 python 列表,然后可能会以某种方式将它们展平。

但到目前为止我还不能这样做。我尝试在 pyspark 中使用用户定义的函数,但它们只返回字符串而不是列表。

FlatMaps 仅适用于 RDD,而不适用于 Dataframe,因此它们不适用。

也许有办法在从 RDD 到数据帧的转换过程中指定这一点。但不知道该怎么做。

【问题讨论】:

    标签: python dataframe pyspark spark-dataframe rdd


    【解决方案1】:

    这是一个只使用 DataFrame 函数的方法:

    df = spark.createDataFrame([('a','b','[q,r,p]'),('c','f','[s,r]')],['col1','col2','col3'])
    
    df=df.withColumn('col4', f.split(f.regexp_extract('col3', '\[(.*)\]',1), ','))
    
    df.select(f.explode('col4').alias('exploded')).groupby('exploded').count().show()
    

    【讨论】:

      【解决方案2】:

      我们可以将 UDF 与 collect_list 一起使用。我试过了,

      >>> from pyspark.sql import functions as F
      >>> from pyspark.sql.types import *
      >>> from functools import reduce
      
      >>> df = spark.createDataFrame([('a','b','[q,r]'),('c','f','[s,r]')],['col1','col2','col3'])
      >>> df.show()
      +----+----+-----+
      |col1|col2| col3|
      +----+----+-----+
      |   a|   b|[q,r]|
      |   c|   f|[s,r]|
      +----+----+-----+
      
      >>> udf1 = F.udf(lambda x : [v for v in reduce(lambda x,y : set(x+y),d) if v not in ['[',']',',']],ArrayType(StringType()))
      ## col3 value is string of list. we concat the strings and set over it which removes duplicates.
      ## Also, we have converted string to set, means it will return [ ] , as values( like '[',']',',').we remove those.
      
      >>> df.select(udf1(F.collect_list('col3')).alias('col3')).first().col3
      ['q', 'r', 's']
      

      不确定性能。希望这会有所帮助。!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-08
        • 2017-11-07
        • 1970-01-01
        • 2018-01-17
        • 2017-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多