首页 > 解决方案 > pyarrow read_csv,每行的列数不同

问题描述

我的 CSV 文件包含 1400 万行,列数不定。前 27 列将始终可用,一行最多可以有 16 列,总共 43 列。

使用香草熊猫我发现了这个解决方法:

largest_column_count = 0
with open(data_file, 'r') as temp_f:
    lines = temp_f.readlines()
    for l in lines:
        column_count = len(l.split(',')) + 1
        largest_column_count = column_count if largest_column_count < column_count else largest_column_count
temp_f.close()

column_names = [i for i in range(0, largest_column_count)]
all_columns_df = pd.read_csv(file, header=None, delimiter=',', names=column_names, dtype='category').replace(pd.np.nan, '', regex=True)

这将创建包含我的所有数据以及数据不可用的空单元格的表格。使用较小的文件,这可以很好地工作。有了完整的文件,我的内存使用量超过了屋顶。

我一直在阅读有关 Apache Arrow 的内容,在尝试加载结构化 csv 文件(每行的列数相同)后,我印象非常深刻。我尝试使用与上述相同的概念加载我的数据文件:

fixed_column_names = [str(i) for i in range(0, 27)]
extra_column_names = [str(i) for i in range(len(fixed_column_names), largest_column_count)]

total_columns = fixed_column_names
total_columns.extend(extra_column_names)

read_options = csv.ReadOptions(column_names=total_columns)
convert_options = csv.ConvertOptions(include_columns=total_columns,
                                     include_missing_columns=True,
                                     strings_can_be_null=True)

table = csv.read_csv(edr_filename, read_options=read_options, convert_options=convert_options)

但我收到以下错误

例外:CSV 解析错误:预期 43 列,得到 32

我需要使用 pyarrow 提供的 csv,否则我将无法创建 pyarrow 表然后转换为 pandas

from pyarrow import csv

有没有人遇到过同样的问题并可以帮助我?

编辑:

修复了第二个代码块

标签: pythonpandascsvpyarrow

解决方案


推荐阅读