使用 pyspark 或 sparksql 进行转换
Transformation using pyspark or sparksql
每当我划分列 E/C 即 40/5 时,我正在尝试某种方法来获得具有逻辑的新输出列,即 40/5 它给出 8 作为划分,我需要采用 E 列数字(不包括末尾零) * 通过股息。即 4,4,4,4,4,4,4,4.
请找到数据框的屏幕截图或 table。
您可以在确定要重复的值和重复次数后使用array_repeat
and array_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|
+---+---+-----------------+
每当我划分列 E/C 即 40/5 时,我正在尝试某种方法来获得具有逻辑的新输出列,即 40/5 它给出 8 作为划分,我需要采用 E 列数字(不包括末尾零) * 通过股息。即 4,4,4,4,4,4,4,4.
请找到数据框的屏幕截图或 table。
您可以在确定要重复的值和重复次数后使用array_repeat
and array_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|
+---+---+-----------------+