【问题标题】:Make single DataFrame from list of Dataframes从数据框列表中制作单个数据框
【发布时间】:2021-01-27 17:02:58
【问题描述】:

我有一个数据框列表, 在列表的每个位置,我都有一个数据框 我需要将所有这些组合在一个数据框中。 这是在 PySpark 中完成的, 在我使用之前

dataframe_new =pd.concat(listName)

解决方案 1

from pyspark.sql.types import *

import pyspark.sql

from pyspark.sql import SparkSession, Row

customSchema = StructType([

  StructField("col1",      StringType(), True),

  StructField("col2", StringType(), True),

  StructField("col3", StringType(), True),

  StructField("col4",  StringType(), True),

  StructField("col5", StringType(), True),

  StructField("col6",  StringType(), True),

  StructField("col7", StringType(), True)

])



df = spark.createDataFrame(queried_dfs[0],schema=customSchema)

我试过的解决方案2:(遍历数据框列表,但不知道如何组合它们

for x in ListOfDataframe
    new_df=union_all()

但这总是创建一个 new_df

任何帮助解决这个问题?

【问题讨论】:

标签: list pyspark apache-spark-sql jupyter-notebook pyspark-dataframes


【解决方案1】:

即使列或列的顺序不同,这也是组合数据框列表的有用功能

def Zconcat(dfs):
    return reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs) 

def union_all(dfs):
    columns = reduce(lambda x, y : set(x).union(set(y)), [ i.columns for i in dfs ]  )

    for i in range(len(dfs)):
        d = dfs[i]
        for c in columns:
            if c not in d.columns:
                d = d.withColumn(c, lit(None))
        dfs[i] = d

    return Zconcat(dfs)

然后传递 union_all 一个数据框列表,例如

union_all([df1, df2, df3])

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 2021-01-07
    • 2020-09-15
    • 2021-09-14
    • 2020-09-21
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多