【问题标题】:How to do data transpose using pyspark, no aggregation, but just reshape如何使用pyspark进行数据转置,没有聚合,只是重塑
【发布时间】:2020-05-14 03:00:15
【问题描述】:

再次,很抱歉提出愚蠢的问题,我是 Pyspark 的新手。 我正在尝试从以下位置转置我的数据集:

   id   dif BA  AB
   1    1   100 30
   1    2   200 40
   1    3   300 20
   1    4   100 15
   2    1   99  18
   2    2   89  9
   3    1   29  20
   3    2   70  32
   3    3   39  13
   4    1   24  14
   4    2   56  23
   4    3   24  26
   5    1   27  31
   5    2   30  17
   6    1   100 19

成为

    id  BA1 BA2 BA3 BA4 AB1 AB2 AB3 AB4
    1   100 200 300 100 30  40  20  15
    2   99  89  NaN NaN 18  9   NaN NaN
    3   29  70  39  NaN 20  32  13  NaN
    4   24  56  24  NaN 14  23  26  NaN
    5   27  30  NaN NaN 31  17  NaN NaN
    6   100 NaN NaN NaN 19  NaN NaN NaN

在 python 中,我使用了以下代码并且它可以工作。

df['AB_idx'] = 'AB' + df.dif.astype(str)
AB = df.pivot(index='id',columns='AB_idx',values='AB').reset_index()

df['BA_idx'] = 'BA' + df.dif.astype(str)
BA = df.pivot(index='id',columns='BA_idx',values='BA').reset_index()

df1=pd.merge(BA, AB, on='id', how='left')

现在的问题是我必须再次翻译成 pyspark,因为我有超过 10 亿条记录。 任何想法?谢谢

我确实看到了类似这篇文章的一些例子:

Pyspark: reshape data without aggregation

但这似乎对我不起作用,因为我有 100 多个不同的差异值。

【问题讨论】:

    标签: pyspark


    【解决方案1】:

    您可以尝试将 agg 设置为 first,然后重命名列:

    output = (df.groupBy("id").pivot("dif")
             .agg(*[F.first(i).alias(i) for i in ["BA","AB"]]).orderBy("id"))
    
    d = dict(zip(output.columns,[''.join(i.split('_')[::-1]) for i in output.columns]))
    output.select(*[F.col(k).alias(v) for k,v in d.items()]).show()
    

    +---+---+---+----+----+----+----+----+----+
    | id|BA1|AB1| BA2| AB2| BA3| AB3| BA4| AB4|
    +---+---+---+----+----+----+----+----+----+
    |  1|100| 30| 200|  40| 300|  20| 100|  15|
    |  2| 99| 18|  89|   9|null|null|null|null|
    |  3| 29| 20|  70|  32|  39|  13|null|null|
    |  4| 24| 14|  56|  23|  24|  26|null|null|
    |  5| 27| 31|  30|  17|null|null|null|null|
    |  6|100| 19|null|null|null|null|null|null|
    +---+---+---+----+----+----+----+----+----+
    

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 1970-01-01
      • 2019-04-08
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多