使用数据流清理 CSV 文件中的数据

Cleaning data in CSV files using dataflow

我正在尝试从 GCS 读取一个 CSV(带有 header)文件,该文件大约有 150 列,然后
1. 为特定列设置列数据
2. 用所有列的空值更新 NaN​​
3. 将 csv 文件(header)写入 GCS

这是棘手的部分:处理是在 Cloud Dataflow 上完成的,这意味着我必须使用 Apache Beam 转换来实现此目的。
我尝试了多种方法,例如 skipping_header_lines 和使用架构

我的管道代码是:


def parse_method(self, line):    
    reader = csv.reader(line.split('\n'))
    for csv_row in reader:
        values = [x.decode('utf8') for x in csv_row]
        row = []
        for value in csv_row:
            if value == 'NaN':
                value = 'Null'
            row.append(value)
    return row

(p
    | 'Read_from_source' >> beam.io.ReadFromText('gs://{0}/test.csv'.format(BUCKET))
    | 'Split' >> beam.Map(lambda s: data_ingestion.parse_method(s))
    | 'Write_to_dest' >> beam.io.WriteToText(output_prefix,file_name_suffix='.csv', num_shards=1))

例如: 如果我的 csv 输入包含;

名称 custom1 custom2
阿伦未定义南
丹尼洛杉矶临时

预期的 csv;
名称 custom1 custom2
阿伦洛杉矶空
丹尼洛杉矶临时

使用以下命令生成您要查找的输出:

    lines = p | ReadFromText(file_pattern="gs://<my-bucket>/input_file.csv")

    def parse_method(line):
        import csv
        reader = csv.reader(line.split('\n'))
        for csv_row in reader:
            values = [x.decode('utf8') for x in csv_row]
            row = []
            for value in csv_row:
                if value == 'NaN':
                    value = 'Null'
                row.append(value)

        return ",".join(row)



    lines = lines | 'Split' >> beam.Map(parse_method)
    line = lines | 'Output to file' >> WriteToText(file_pattern="gs://<my-bucket>/output_file.csv")

现在要编辑基于 header 的列,我不确定是否有更直接的方法,但我会按以下方式使用 pandas:

    lines = p | "ReadFromText" >> ReadFromText(file_pattern="gs://<my-bucket>/input_file.csv")

    def parse_method(line):
        import pandas as pd

        line = line.split(',')
        df = pd.DataFrame(data=[line],columns=['name','custom1','custom2'])
        df['custom2'] = df.custom2.apply(lambda x: 'None' if x == 'Nan' else x)
        values = list(df.loc[0].values)
        return ",".join(values)

    lines = lines | "Split" >> beam.Map(parse_method)
    line = lines | "Output to file" >> WriteToText(file_path_prefix="gs://<my-bucket>/output_file.csv")