如何在python中预处理非常大的数据

如何在python中预处理非常大的数据,python,machine-learning,Python,Machine Learning,我有两个文件,每个100 MB。这些文件的格式如下所示: 0 1 2 5 8 67 9 122 1 4 5 2 5 8 0 2 1 5 6 ..... for train in train_files: with open(train) as f: row = [] col = [] for index, line in enumerate(f): record = line.r

我有两个文件,每个100 MB。这些文件的格式如下所示:

0  1  2  5  8  67  9  122
1  4  5  2  5  8
0  2  1  5  6
.....
for train in train_files:  
    with open(train) as f:
        row = []
        col = []
        for index, line in enumerate(f):
            record = line.rstrip().split(' ')
            row = row+[index]*(len(record)-4)
            col = col+record[4:]
        row = np.array(row)
        col = np.array(col)
        data = np.array([1]*len(row))
        mtx = sparse.coo_matrix((data, (row, col)), shape=(n_row, max_feature))
        mmwrite(train+'trans',mtx)
(请注意,实际文件中没有添加对齐空间,每个元素之间只有一个空间,添加对齐以获得美观效果)

每行中的第一个元素是它的二进制分类,其余的行是值为1的特征索引。例如,第三行表示该行的第二、第一、第五和第六个特征为1,其余为零

我尝试读取每个文件中的每一行,并使用sparse.coo_matrix创建如下稀疏矩阵:

0  1  2  5  8  67  9  122
1  4  5  2  5  8
0  2  1  5  6
.....
for train in train_files:  
    with open(train) as f:
        row = []
        col = []
        for index, line in enumerate(f):
            record = line.rstrip().split(' ')
            row = row+[index]*(len(record)-4)
            col = col+record[4:]
        row = np.array(row)
        col = np.array(col)
        data = np.array([1]*len(row))
        mtx = sparse.coo_matrix((data, (row, col)), shape=(n_row, max_feature))
        mmwrite(train+'trans',mtx)
但这花了很长时间才完成。我开始在晚上读取数据,让电脑在我睡觉后运行,当我醒来时,它仍然没有完成第一个文件


处理此类数据的更好方法是什么?

我认为这比您的方法快一点,因为它不逐行读取文件。您可以使用一个文件的一小部分尝试此代码,并与您的代码进行比较。
此代码还要求提前知道功能部件编号。如果我们不知道功能编号,则需要另一行被注释掉的代码

import pandas as pd
from scipy.sparse import lil_matrix
from functools import partial


def writeMx(result, row):
    # zero-based matrix requires the feature number minus 1
    col_ind = row.dropna().values - 1
    # Assign values without duplicating row index and values
    result[row.name, col_ind] = 1


def fileToMx(f):
    # number of features
    col_n = 136
    df = pd.read_csv(f, names=list(range(0,col_n+2)),sep=' ')
    # This is the label of the binary classification
    label = df.pop(0)
    # Or get the feature number by the line below
    # But it would not be the same across different files
    # col_n = df.max().max()
    # Number of row
    row_n = len(label)
    # Generate feature matrix for one file
    result = lil_matrix((row_n, col_n))
    # Save features in matrix
    # DataFrame.apply() is usually faster than normal looping
    df.apply(partial(writeMx, result), axis=0)
    return(result)

for train in train_files:
    # result is the sparse matrix you can further save or use
    result = fileToMx(train)
    print(result.shape, result.nnz)
    # The shape of matrix and number of nonzero values
    # ((420, 136), 15)

n_row==30000==0
永远不会成为真的。哈!我的错。我加上它是为了做一些检查。当我真的运行这个代码时,我说了什么?当你得到稀疏矩阵后,你的目标/目的是什么?如果内存不是问题,你可以考虑多重处理。您的代码非常有用,但我无法使用    df=pd.read_csv(f,sep=“”,header=None),因为每行的长度不同。我终于明白了为什么运行我的代码要花很长时间。这是因为每次我将一个列表附加到预先存在的列表中,它都必须为该列表分配一个新的内存空间。因此,随着名单越来越大,这样做的时间也越来越长。我通过为矩阵分配一个固定的大内存来解决这个问题,而且工作起来很有趣。几秒钟就完成了。谢谢你的建议@很高兴听到你成功了。抢手货我修好了。代码现在应该可以工作了。