【问题标题】:Assigning a sequence number to a set将序列号分配给集合
【发布时间】:2022-11-03 05:35:35
【问题描述】:

记录集由 3 种记录类型 01、11、19 组成。

recType Value
01 8888
11 asssff
19 78292
01 77777
11 aslasd
19 08325

我想创建一个 '''sequence''' 列,以便我拥有记录集的唯一标识符。我尝试了 '''groupby''' 和 '''aggregate''' 但我没有得到我想要的。所需的输出数据帧如下:

recType Value sequence
01 8888 1
11 asssff 1
19 78292 1
01 77777 2
11 aslasd 2
19 08325 2

请帮助。

【问题讨论】:

  • 因为 spark 是分布式的,所以可能会出现 asssff 可能出现在 77777 之后(在序列 2 中)而不是 8888 (在序列 1 中)的情况。是否有任何字段可以识别数据帧的顺序?
  • 你好@samkart,数据框只能在 recType 字段上排序。它以 01 开始,以 19 结束。01 recType 表示新记录集的开始。实际上它具有多种记录类型的固定宽度文件。所以我们试图通过添加一个名为'''sequence'''的新列来对记录集进行分组。
  • 如果你混合所有的行,你怎么知道哪个 01 会进入第一个序列? 7777 还是 8888?
  • 您好@ZygD,这是从文本文件中读取数据框后的外观。 01 的顺序与文本文件一致。
  • 您是直接在 spark 中阅读它还是在 pandas (fwf) 中第一次阅读?

标签: apache-spark pyspark


【解决方案1】:
new = (df.withColumn('sequence', collect_list('recType').over(Window.partitionBy().orderBy().rowsBetween(Window.unboundedPreceding,0)))#Put all recType in a list starting from all before to current
       #Check if recType exists in the new list.This will return a bool.
       #Cast bool into integer and sum all elements in the array
       .withColumn('sequence', expr("aggregate(transform(sequence, c-> cast(c == recType as int)),0, (k,l)->k+l)")) 
      
      ).show(truncate=False)


+-------+------+--------+
|recType|Value |sequence|
+-------+------+--------+
|01     |8888  |1       |
|11     |asssff|1       |
|19     |78292 |1       |
|01     |77777 |2       |
|11     |aslasd|2       |
|19     |08325 |2       |
+-------+------+--------+

【讨论】:

    猜你喜欢
    • 2022-06-14
    • 2019-07-12
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多