在python中从文件中读取大数据的有效方法

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

我有10000个文件,每个文件有2000个样本。每个文件都以下列模式编写:

discoal 4 2000 55000 -Pt 1750.204699 17502.046985 -Pre 19252.251684 57756.755051
939889312 676473727

###Example 1
//
segsites: 3
positions: 0.000616 0.001428 0.001500
100
001
101
100

###Example 2
segsites: 6
positions: 0.001843 0.002019 0.002102 0.002431 0.003427 0.004103 
000101
101000
001100
110111

文件详情:

每个文件都以discoal和带有两个数字的行开头。这些行将被忽略。所需的数据是segsites,position和我在位置后的二进制值。每行(二进制值)将对应于矩阵中的行。

segsite的数量将对应于位置向量的长度和二进制矩阵中的列数。例如,在第一个例子中,我的segsites是3,因此我的位置向量也有3个值。我的二进制矩阵大小为4 x 3.它是'4',因为示例中有四行二进制值。

我的代码完成了所有这些。但我想只保留那些segsites小于5000的例子。

这只是一个例子。否则我的segsites高达10000.我已经制作了一个遍历所有这些文件的代码。并且对于这些文件中的每一个,它获得隔离站点的数量,位置并将二进制值放在位置下面的矩阵中。例如,对于第一个例子,矩阵的尺寸为4×3,第二个尺寸为4×6。

我的代码是:

def reading_filenames(path_to_directory,extension,tot_segsites,positions,snp_matrix):
    """
    This function returns the file names in the directory of interest
    """

    path = path_to_directory + extension 
    files = glob.glob(path)

    i=0
    for file in files:     
        f=open(file, 'r')  
        #print('file : ',file)
        reading_file(f.readlines(),tot_segsites,positions,snp_matrix,i)
        i += 1

        f.close() 

    return files, snp_matrix

    #return [f for f in os.listdir(path_to_directory) if f.endswith(extension)]

def reading_file(file,tot_segsites,positions,snp_matrix,i):

    flag = False
    length = 0
    counter = 0
    array = np.zeros((chrm_num,6000))
    for line in file:
        if 'segsites:' in line:
            lst = (line.strip('\n').split(': '))
            res = int(lst[1])
            tot_segsites.append(res)

        elif 'position' in line:
            lst = line.strip('\n').split(': ')
            lst = lst[1:]
            res = [float(k) for k in lst[0].split(' ')]

            for j in range(len(res)):
                positions[i][j] = res[j]

            flag = True

        elif flag:
            lst = line.strip('\n')
            reading_snp_matrix(lst,length,chrm_num,counter,array)
            counter += 1
            flag = True

    snp_matrix.append((array))
    return snp_matrix

def reading_snp_matrix(line,length,chrm_num,counter,array):
    chromosome = list(map(int, line))
    for i in range(len(chromosome)):
        array[counter][i] = chromosome[i]

reading_filenames函数只读取文件夹中的文件,并为每个文件调用函数reading_file。然后read_file函数读取segsites,position和binary matrix。但是,我想更改此代码,以便只存储那些segsite为5000或更少但不多的segsites,position和binary matrix。我不知道如何使用我制作的代码实现这一目标。另外,你能告诉我一种有效的方式来阅读我提到的格式的文件。因为这段代码很慢。

python-3.x file-read
1个回答
0
投票

您可以读取您的文件,将其转换为csv,再次写入(一次)。然后你可以使用pandas来读取csv并轻松操作它

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