【问题标题】:Merge dataframes in Pyspark with same column names在 Pyspark 中合并具有相同列名的数据框
【发布时间】:2021-05-12 12:15:26
【问题描述】:

在使用 pyspark 连接时,后缀有什么替代品吗? 要么 当使用spark.sql(query)

数据框有相同的列,我想保留它们各自的数据框名称作为后缀。

下面的代码是我在 python 中所做的。

df = pd.merge(left = df1, right = df2, on= 'col1', how= 'inner', suffixes= ('_df1', '__df2'))
df = pd.merge(left = df, right = df3, on= 'vin_17', how= 'inner', suffixes= ('','__df3'))
df = pd.merge(left = df, right = df4, on= 'vin_17', how= 'inner', suffixes= ('','__df4'))

这就是我在 pyspark 中的做法,但随后所有列名都在更改,我希望重复的列仅具有 __suffix

df1 = df1.select(*(col(x).alias(x + '__df1') for x in df1.columns))
df2 = df2.select(*(col(x).alias(x + '__df2') for x in df2.columns))
df3 = df3.select(*(col(x).alias(x + '__df3') for x in df3.columns))

【问题讨论】:

    标签: python pyspark apache-spark-sql pyspark-dataframes


    【解决方案1】:

    重命名时,您只能过滤 3 个数据框之间的公共列:

    def get_common_cols(dfs: list):
        seen = set()
        repeated = set()
        for l in [df.columns for df in dfs]:
            for i in set(l):
                if i in seen:
                    repeated.add(i)
                else:
                    seen.add(i)
    
        return list(repeated)
    
    common = get_common_cols([df1, df2, df3])
    
    # rename only if x exists in common_cols
    df1 = df1.select(*[col(x).alias(f"{x}__df1" if x in common else x) for x in df1.columns])
    df2 = df2.select(*[col(x).alias(f"{x}__df2" if x in common else x) for x in df2.columns])
    df3 = df3.select(*[col(x).alias(f"{x}__df3" if x in common else x) for x in df3.columns])
    

    【讨论】:

    • 普通行返回空列表,
    • list(set.intersection(*[set(cols) for cols in all_cols]))
    • @user12063090 空列表是什么意思?空?
    • 是的,一个空集。我尝试使用另一个临时列表 p= [[ 'name1', 'name2'], ['name3', 'name1']] list(set.intersection(*[set(cols) for cols in p]))也返回空集
    • p= [[ 'name1', 'name2'], ['name1', 'name3']] 如果名称 1 在第一个位置,则只有它返回 name1 ,但事实并非如此在我的数据框中,列不在同一位置,有些在最后,有些在第一个位置
    猜你喜欢
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2012-11-26
    相关资源
    最近更新 更多