PySpark透视 [英] PySpark Pivoting

查看:64
本文介绍了PySpark透视的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PySpark从许多表中透视数据,但是我需要以一种奇怪的方式来做.请参见下面的示例.

I want to use PySpark to pivot data from a number of tables but i need to do it in a strange way. Please see below for an example.

原始表:

Vehicle_id | Owner_ID    | Vehicle_Buy_Date
--------------------------------------------
1          | 1           | 01/01/2015
1          | 2           | 01/10/2014
2          | 1           | 10/10/2016

最终结果:

Vehicle_id | Owner_1_Buy_Date | Owner_2_Buy_Date
------------------------------------------------
1          |01/01/2015        |01/10/2014
2          |10/10/2016        |NULL

我知道这是一个不常见的问题,因为这通常不是在数据库表上完成的.

I understand that this is an unusual question to ask, as this isn't mostly done on database tables.

在PySpark中有什么方法可以进行这种类型的旋转吗?

Is there any way of doing this type of pivoting in PySpark?

推荐答案

尝试使用此代码来获得所需的结果:

Try to use this code to get the required result:

NewDf = df.withColumn('id', F.concat(F.lit('Owner_'), F.col('owner_id'), F.lit('_Buy_Date')).groupBy('Vehicle_id').pivot('id').agg(F.first('Vehicle_Buy_Date'))

这篇关于PySpark透视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆