使用python将两个spark数据帧合并到一个模式中

2024-06-07 06:06:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不同的pyspark数据帧,需要合并成一个。合并时需要对一些逻辑进行编码。其中一个数据帧具有以下模式:(id,type,count),另一个具有以下模式:(id,timestamp,test1,test2,test3)

第一个数据帧是通过sql“GROUPBY”查询创建的。可以有重复的ID,但ID的类型不同。并且,给定类型有一个关联计数

在最终模式(合并模式)中,类型计数将有不同的列。从第一个架构检索计数数据

最后一个模式示例:(id、时间戳、test1、test2、test3、type1count、type2count、type3count)

我现在的做法是使用两个for循环来构建字典。我有一个空的模式,我使用字典来更新模式。如果我这样做,我就不会真正使用spark功能

schema1: (id, type, count) -- type has the values type1, type2, type3
schema2: (id, timestamp, test1, test2, test3)
finalschema: (id, timestamp, test1, test2, test3, type1count, type2count, type3count)

有人对如何改进这一点有什么建议吗

非常感谢


Tags: 数据id类型typecount模式timestamp计数
2条回答

您可以在id列上连接上面两个dataframe,下面是相同的示例代码段

df1 schema is (id, type, count).
df2 schema is (id, timestamp, test1, test2, test3, type1count, type2count, type3count)

merged_df = df1.join(df2, on=['id'], how='left_outer')

希望这会有所帮助

在将第一个数据帧与第二个数据帧联接之前,可以使用Pyspark pivot函数来透视第一个数据帧

工作示例:

import pyspark.sql.functions as F
import pyspark.sql.functions as F
df = spark.createDataFrame([[1,'type1',10],
                            [1,'type2',10],
                            [1,'type3',10]],
                           schema=['id','type','quantity'])

df = df.groupBy('id').pivot('type').sum('quantity')
display(df)

您可以随意更改聚合

相关问题 更多 >