Assigningparenttosparkrow
创始人
2024-09-20 18:00:08
0

将Spark行分配给父行

通常在处理具有分层结构的数据时,我们会需要为Spark DataFrame中的每一行分配一个父行。这可以通过使用Spark中的Column(列)和struct(结构)类型来实现。

例如,考虑以下数据:

id parent
1 null
2 1
3 1
4 2
5 3

要将每个行Spark分配给其父行,我们可以使用withColumn函数并使用struct类型来创建一个新列。下面是例子:

from pyspark.sql.functions import struct

df = spark.createDataFrame([(1, None), (2, 1), (3, 1), (4, 2), (5, 3)], ["id", "parent"])

Assign parent to each row

df = df.withColumn("row_and_parent", struct("*", "parent"))

Show the result

df.show()

输出结果如下:

+---+------+----------------+ | id|parent| row_and_parent| +---+------+----------------+ | 1| null| [1,null] | | 2| 1| [2,1] | | 3| 1| [3,1] | | 4| 2| [4,2] | | 5| 3| [5,3] | +---+------+----------------+

现在,我们可以访问每行的父行并执行操作。例如,要过滤具有id = 4的行的父行,我们可以使用以下代码:

Filter rows with id=4 and its parent row

df.filter("id = 4 or row_and_parent.parent = 4").show()

输出结果:

+---+------+----------------+ | id|parent| row_and_parent| +---+------+----------------+ | 2|

相关内容

热门资讯

四分钟项目!wpk模拟器(透视... 四分钟项目!wpk模拟器(透视)切实是真的有辅助插件(哔哩哔哩)亲,关键说明,wpk模拟器透视脚本安...
十分钟举措!aa poker辅... 十分钟举措!aa poker辅助(透视)都是是有辅助插件(哔哩哔哩)1、aa poker辅助公共底牌...
第2分钟演示!hhpoker底... 第2分钟演示!hhpoker底牌透视脚本(透视)好像真的有辅助开挂(哔哩哔哩)1、每一步都需要思考,...
六分钟方针!wepoker黑侠... 六分钟方针!wepoker黑侠破解(透视)切实是真的有辅助安装(哔哩哔哩)1、wepoker黑侠破解...
第1分钟阶段!fishpoke... 第1分钟阶段!fishpoker透视底牌(透视)其实有辅助辅助(哔哩哔哩)1、fishpoker透视...
六分钟技法!we-poker辅... 六分钟技法!we-poker辅助器(透视)其实存在有辅助神器(哔哩哔哩)1、we-poker辅助器免...
九分钟教程书!aapoker安... 九分钟教程书!aapoker安装包怎么使用(透视)果然是真的有辅助辅助(哔哩哔哩)1、实时aapok...
第四分钟策略!pokemmo辅... 第四分钟策略!pokemmo辅助器手机版下载(透视)总是真的有辅助透视(哔哩哔哩)1、很好的工具软件...
3分钟办法!约局吧游戏挂(透视... 3分钟办法!约局吧游戏挂(透视)一贯存在有辅助安装(哔哩哔哩)1)约局吧游戏挂免费钻石:进一步探索约...
8分钟手筋!hhpoker透视... 8分钟手筋!hhpoker透视方法(透视)竟然存在有辅助神器(哔哩哔哩)1、上手简单,内置详细流程视...