【问题标题】:Merge two spark dataframes with different columns to get all columns合并具有不同列的两个 spark 数据框以获取所有列
【发布时间】:2021-08-19 17:23:40
【问题描述】:

假设我有 2 个 spark 数据帧:

Location    Date        Date_part   Sector      units   
USA         7/1/2021    7/1/2021    Cars        200     
IND         7/1/2021    7/1/2021    Scooters    180     
COL         7/1/2021    7/1/2021    Trucks      100     
Location    Date    Brands  units   values    
UK          null    brand1  400     120       
AUS         null    brand2  450     230       
CAN         null    brand3  150     34        

我需要我的结果数据框

Location    Date        Date_part   Sector      Brands  units   values
USA         7/1/2021    7/1/2021    Cars                200     
IND         7/1/2021    7/1/2021    Scooters            180     
COL         7/1/2021    7/1/2021    Trucks              100
UK          null        7/1/2021                brand1  400     120
AUS         null        7/1/2021                brand2  450     230
CAN         null        7/1/2021                brand3  150     34

所以我想要的 df 应该包含来自两个数据框的所有列,我也需要所有行中的 Date_part 这是我尝试过的:

df_result= df1.union(df_2)

但我得到了这个作为我的结果。值正在交换,第二个数据框中的一列丢失。

Location    Date        Date_part   Sector      Brands  units
USA         7/1/2021    7/1/2021    Cars        200     
IND         7/1/2021    7/1/2021    Scooters    180     
COL         7/1/2021    7/1/2021    Trucks      100
UK          null        brand1                  400     120
AUS         null        brand2                  450     230
CAN         null        brand3                  150     34

有什么好的建议

【问题讨论】:

    标签: python apache-spark pyspark


    【解决方案1】:

    union :此函数按位置(不是按名称)解析列

    这就是您认为“正在交换值并且第二个数据帧中的一列丢失的原因。”

    您应该使用unionByName,但此功能要求两个数据框具有相同的结构。

    我为您提供了这个简单的代码来协调数据框的结构,然后执行 union(ByName)。

    from pyspark.sql import DataFrame
    from pyspark.sql import functions as F
    
    def add_missing_columns(df: DataFrame, ref_df: DataFrame) -> DataFrame:
        """Add missing columns from ref_df to df
    
        Args:
            df (DataFrame): dataframe with missing columns
            ref_df (DataFrame): referential dataframe
    
        Returns:
            DataFrame: df with additionnal columns from ref_df
        """
        for col in ref_df.schema:
            if col.name not in df.columns:
                df = df.withColumn(col.name, F.lit(None).cast(col.dataType))
    
        return df
    
    
    df1 = add_missing_columns(df1, df2)
    df2 = add_missing_columns(df2, df1)
    
    df_result = df1.unionByName(df2)
    

    【讨论】:

    • 谢谢@Steven :) 这很完美!!但有一件事是在 date_part 列中,我得到了空值。但是是否可以使用 df1 和 date 列中的值获取 date_part 列以具有 null 和 date 值?
    • @user175025 你应该问另一个问题。那是一个不同的问题。我无法在评论中回答这个问题。
    • 请找到这个链接:[link]stackoverflow.com/questions/68846254/…
    猜你喜欢
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2017-06-24
    相关资源
    最近更新 更多