【问题标题】:How to get the index of the highest value in a list per row in a Spark DataFrame? [PySpark]如何获取 Spark DataFrame 中每行列表中最大值的索引? [PySpark]
【发布时间】:2020-01-28 23:34:54
【问题描述】:

我已经完成了 LDA 主题建模,并将其存储在 lda_model

在转换我的原始输入数据集后,我检索了一个 DataFrame。其中一列是 topicDistribution,其中该行属于 LDA 模型中每个主题的概率。因此,我想获取每行列表中最大值的索引。

df -- | 'list_of_words' | 'index ' | 'topicDistribution' | 
       ['product','...']     0       [0.08,0.2,0.4,0.0001]
          .....             ...         ........

我想转换 df 以便添加一个额外的列,它是每行 topicDistribution 列表的 argmax。

df_transformed --  | 'list_of_words' | 'index' | 'topicDistribution' | 'topicID' |
                    ['product','...']     0     [0.08,0.2,0.4,0.0001]      2
                       ......            ....         .....              ....

我该怎么做?

【问题讨论】:

    标签: python apache-spark pyspark rdd


    【解决方案1】:

    您可以创建一个用户定义的函数来获取最大值的索引

    from pyspark.sql import functions as f
    from pyspark.sql.types import IntegerType
    
    max_index = f.udf(lambda x: x.index(max(x)), IntegerType())
    df = df.withColumn("topicID", max_index("topicDistribution"))
    

    例子

    >>> from pyspark.sql import functions as f
    >>> from pyspark.sql.types import IntegerType 
    >>> df = spark.createDataFrame([{"topicDistribution": [0.2, 0.3, 0.5]}])
    >>> df.show()
    +-----------------+
    |topicDistribution|
    +-----------------+
    |  [0.2, 0.3, 0.5]|
    +-----------------+
    
    >>> max_index = f.udf(lambda x: x.index(max(x)), IntegerType())
    >>> df.withColumn("topicID", max_index("topicDistribution")).show()
    +-----------------+-------+
    |topicDistribution|topicID|
    +-----------------+-------+
    |  [0.2, 0.3, 0.5]|      2|
    +-----------------+-------+
    

    编辑:

    由于您提到topicDistribution 中的列表是numpy 数组,您可以更新max_index udf 如下:

    max_index = f.udf(lambda x: x.tolist().index(max(x)), IntegerType())
    

    【讨论】:

    • 我收到以下错误 AttributeError: 'numpy.ndarray' object has no attribute 'index'
    • @kspr 您没有提到您在 topicDistribution 中的数据是一个 numpy 数组。检查我的编辑
    猜你喜欢
    • 2021-08-25
    • 2018-06-09
    • 2019-03-17
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 2022-07-25
    • 2021-07-19
    • 2022-01-05
    相关资源
    最近更新 更多