首页 > 解决方案 > 从python并行执行bash任务,提取csv列

问题描述

我有一个包含 7,221,032 列和 37 行的 csv 文件。我需要将每一列映射到一个单独的文件,最好是从 python 脚本。到目前为止我的尝试:

num_features = 7221032
binary_dir = "data_binary"

command_template = command = 'awk -F "\\"*,\\"*" \'{print $%s}\' %s/images_binary.txt > %s/feature_files/pixel_%s.vector'

batch_size = 100

batch_indexes = np.arange(1, num_features, batch_size)

for batch_index in batch_indexes[1:5]:

    indexes = range(batch_index-batch_size, batch_index)

    commands = [command_template % (str(i), binary_dir, binary_dir, str(i)) for i in indexes]
    map(os.system, commands)

但是,这似乎是一个相当缓慢的过程。关于如何加快它的任何建议?

标签: pythonbash

解决方案


修改后的解决方案 - 使用 Perl

使用 perl prog.pl < /path/to/images_binary.txt 运行

100,000 个项目的运行时间为 10 秒。完整的数据集大约需要 7 个小时。不确定并行运行会更好,因为瓶颈是文件的打开/关闭。提高性能的最佳选择是减少生成文件的数量,以某种方式首先按列顺序写入输入。

#! /usr/bin/perl

while ( my $x = <> ) {
    chomp $x ;
    my @v = split(',', $x) ;
    foreach my $i (0..$#v) {
        open OF, ">data_binary/feature_files/pixel_$i.vector" ;
        print OF $v[$i], "\n" ;
        close OF ;
    } ;
} ;

推荐阅读