拆分具有不一致列号的csv文件

问题描述 投票:0回答:1

我有一个CSV文件格式如下,除了它是大约2000万行:

A,B,C,D
1,2,3,4
1,1,3,4
1,0,0,1,4,3
1,0,5,6,2,1

我尝试用这样的熊猫阅读:

df = pd.read_csv(_out_path, sep=',', engine='c') # engine c because it's faster

这导致以下错误:

ParserError: Error tokenizing data. C error: Expected 18 fields in line 13674206, saw 31

使用上面的测试文件,pandas会处理这个并添加两个未命名的列,前两行包含np.NAN。

A   B   C   D   Unnamed: 4  Unnamed: 5
0   1   2   3   4   NaN NaN
1   1   1   3   4   NaN NaN
2   1   0   0   1   4.0 3.0
3   1   0   5   6   2.0 1.0

但是,对于真实文件(遗憾的是,我无法共享),会导致上述错误。

我正在寻找一种方法来解决它,找到逗号最多的行,计算逗号的数量,并添加逗号作为每行的需要,以便大熊猫读取文件。或者理想情况下,无论如何都要以更简单的方式读取文件。


编辑:

数据已经从几百个CSV文件中连接起来,但是在中间添加了新的列(遗憾的是并非全部都在最后)。因此,一个好的解决方案(感谢评论)将分割文件nr的条目更改。

此外,文件中没有标题。我试着在这个例子的第一行手动添加它们,所以我想在分割文件后我必须添加标题。

python python-3.x pandas
1个回答
2
投票

为了拥有干净的数据集,最好将它们分成单独的文件。

如果列数仅上升且永不下降,您可以使用字典轻松跟踪不​​同的目标文件:

source_file = open('mixed_data.csv', 'r')

destination_files = {}

for line in source_file:
    item_count = len(line.split(','))

    try:
        dest_file = destination_files[item_count]

    except KeyError:
        file_name = 'split_data_' + str(item_count) + '.csv'
        dest_file = destination_files[item_count] = open(file_name, 'w')

    dest_file.write(line)

for dest_file in destination_files.values():
    dest_file.close()

source_file.close()

如果程序在之后结束或者文件对象被绑定的范围被保留,那么关闭并不是绝对必要的,但无论如何它都是好的做法。

© www.soinside.com 2019 - 2024. All rights reserved.