【问题标题】:How do I Programmatically parsed a fixed width text file in Pyspark?如何在 Pyspark 中以编程方式解析固定宽度的文本文件?
【发布时间】:2017-09-08 14:16:21
【问题描述】:

这篇文章很好地展示了如何使用 pyspark (pyspark parse text file) 将固定宽度的文本文件解析为 Spark 数据帧。

我有几个要解析的文本文件,但它们的架构略有不同。与其像上一篇文章所建议的那样为每个人写出相同的过程,我想编写一个通用函数,它可以在给定宽度和列名的情况下解析一个固定宽度的文本文件。

我对 pyspark 很陌生,所以我不确定如何编写一个 select 语句,其中列数及其类型是可变的。

任何帮助将不胜感激!

【问题讨论】:

    标签: apache-spark pyspark spark-dataframe


    【解决方案1】:

    假设我们有一个类似于示例线程中的文本文件:

    00101292017you1234
    00201302017 me5678
    

    "/tmp/sample.txt"。以及包含每个文件名、列列表和宽度列表的字典:

    schema_dict = {
        "sample": {
            "columns": ["id", "date", "string", "integer"], 
            "width" : [3, 8, 3, 4]
        }
    }
    

    我们可以加载数据帧并将它们迭代地拆分为列,使用:

    import numpy as np
    
    input_path = "/tmp/"
    df_dict = dict()
    for file in schema_dict.keys():
        df = spark.read.text(input_path + file + ".txt")
        start_list = np.cumsum([1] + schema_dict[file]["width"]).tolist()[:-1]
        df_dict[file] = df.select(
            [
                df.value.substr(
                    start_list[i], 
                    schema_dict[file]["width"][i]
                ).alias(schema_dict[file]["columns"][i]) for i in range(len(start_list))
            ]
        )
    
        +---+--------+------+-------+
        | id|    date|string|integer|
        +---+--------+------+-------+
        |001|01292017|   you|   1234|
        |002|01302017|    me|   5678|
        +---+--------+------+-------+
    

    【讨论】:

    • 真的很喜欢这个解决方案。不错的尝试!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多