【问题标题】:Transformation using pyspark or sparksql使用 pyspark 或 sparksql 进行转换
【发布时间】:2022-01-13 05:02:19
【问题描述】:

每当我将列 E/C (即 40/5)除以 8 作为除数时,我正在尝试某种方法来获得具有逻辑的新输出列,我需要将列 E 数字(不包括结尾零)* 除以除数。即 4,4,4,4,4,4,4,4。

请查找数据框或表格的屏幕截图。

【问题讨论】:

    标签: azure dataframe pyspark apache-spark-sql


    【解决方案1】:

    您可以在确定要重复的值和要重复的次数后使用array_repeatarray_join

    工作示例

    from pyspark.sql.functions import array_repeat, array_join, col as c, floor, lit, when
    from pyspark.sql import Column
    
    data = [(5, 40, ), (10, 80, ), (20, 120, )]
    
    df = spark.createDataFrame(data, ("C", "E", ))
    
    def repetition(col_c: Column, col_e: Column) -> Column:
        times_to_repeat = floor(c("E") / c("C")).cast("int")
        value_to_repeat = when(c("E") % lit(10) == 0, (c("E") / lit(10)).cast("int")).otherwise(c("E"))
        value_repeat = array_repeat(value_to_repeat, times_to_repeat)
        return array_join(value_repeat, ",")
    
    df.withColumn("Newoutput", repetition(c("C"), c("E"))).show(100, False)
    

    输出

    +---+---+-----------------+
    |C  |E  |Newoutput        |
    +---+---+-----------------+
    |5  |40 |4,4,4,4,4,4,4,4  |
    |10 |80 |8,8,8,8,8,8,8,8  |
    |20 |120|12,12,12,12,12,12|
    +---+---+-----------------+
    

    【讨论】:

    • 你好 Snithish ,谢谢你 我也差不多在路上 array_join 我忘了用现在它工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多