【问题标题】:Append new column to a dataframe by reading parquet files first通过首先读取镶木地板文件将新列附加到数据框
【发布时间】:2020-06-15 15:27:37
【问题描述】:

假设有一个包含多列的数据框,看起来像这样(我省略了不必要的列):

+----------------------------------------+
|path                                    |
+----------------------------------------+
|/tmp/some_folder/2020-04-02/blabla1.parq|
|/tmp/some_folder/2020-05-14/bla2bla.parq|
+----------------------------------------+

其中 path 是 hdfs 中的某个 parquet 文件,它只有一行,结构如下:

+-----------+
|value      |
+-----------+
|some value |
+-----------+

如何读取这些文件并向初始数据框添加一列(“值”)?结果,我想要这样的结构:

+----------------------------------------+----------+
|path                                    |value     |
+----------------------------------------+----------+
|/tmp/some_folder/2020-04-02/blabla1.parq|some value|
|/tmp/some_folder/2020-05-14/bla2bla.parq|bla blah  |
+----------------------------------------+----------+

例如,我可以将“路径”列转换为列表,通过迭代将其读入数据帧并与初始数据帧连接。还有其他解决方案吗?最好在性能方面更快。

【问题讨论】:

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


    【解决方案1】:

    您可以通过使用 input_file_name() 来避免加入,以便将 path 添加到数据帧中。

    Example:

    from pyspark.sql.functions import *
    from pyspark.sql.types import *
    
    paths=df.select("path").rdd.map(lambda x:x[0]).collect()
    
    #schema will the fields
    sch=StructType([StructField("path",StringType()),StructField("value",StringType())])
    final_df=spark.createDataFrame([],schema)
    
    for path in paths:
        final_df=spark.read.parquet(path).withColumn("path",input_file_name())
    
    #dataframe will have path and value to it
    final_df.show()
    

    【讨论】:

      【解决方案2】:

      我通过一次读取多个 parquet 文件解决了这个问题:spark.read.parquet(f"/tmp/some_folder/{2020-04-02/blabla1.parq, 2020-05-14/bla2bla.parq}") 然后使用 input_file_name() 添加“路径”列。

      【讨论】:

        猜你喜欢
        • 2019-12-22
        • 2017-01-07
        • 2019-11-20
        • 2019-08-04
        • 2022-06-16
        • 2023-02-07
        • 1970-01-01
        • 2019-09-23
        • 1970-01-01
        相关资源
        最近更新 更多