读取大型表文件,但使用 pandas 仅保留一小部分行



我有一个大表文件(大约 2 GB(,其中包含一个按其第一列索引的距离矩阵。它的行看起来像

A 0 1.2 1.3 ...
B 1.2 0 3.5 ...
C 1.5 0 4.5 ...

但是,我只需要保留一小部分行。如果给我一个需要保留的索引列表,那么将此文件读入 pandas 数据帧的最佳和最快方法是什么?现在,我正在使用

distance_matrix = pd.read_table("hla_distmat.txt", header = None, index_col = 0)[columns_to_keep]

以读取文件,但这在使用 read_table 命令时遇到了内存问题。有没有更快、更节省内存的方法可以做到这一点?谢谢。

如果需要

过滤器列和过滤器行的skiprows,则需要usecols参数,您必须指定必须通过listrangenp.array删除哪一列:

distance_matrix = pd.read_table("hla_distmat.txt", 
                                 header = None, 
                                 index_col = 0, 
                                 usecols=[columns_to_keep],
                                 skiprows = range(10, 100))

示例:(在实际数据中省略sep参数,sep='t'默认在read_table中(

import pandas as pd
import numpy as np 
from pandas.compat import StringIO
temp=u"""0;119.02;0.0
1;121.20;0.0
3;112.49;0.0
4;113.94;0.0
5;114.67;0.0
6;111.77;0.0
7;117.57;0.0
6648;0.00;420.0
6649;0.00;420.0
6650;0.00;420.0"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
columns_to_keep = [0,1]
df = pd.read_table(StringIO(temp), 
                   sep=";", 
                   header=None,
                   index_col=0, 
                   usecols=columns_to_keep,
                   skiprows = range(5, 100))
print (df)
        1
0        
0  119.02
1  121.20
3  112.49
4  113.94
5  114.67

更通用的解决方案与numpy.setdiff1d

#if index_col = 0 always need first column (0)
columns_to_keep = [0,1]
#for keep second, third, fifth row
rows_to_keep = [1,2,4]
#estimated row count or use solution from http://stackoverflow.com/q/19001402/2901002
max_rows = 100
df = pd.read_table(StringIO(temp), 
                   sep=";", 
                   header=None,
                   index_col=0, 
                   usecols=columns_to_keep,
                   skiprows = np.setdiff1d(np.arange(max_rows), np.array(rows_to_keep)))
print (df)
        1
0        
1  121.20
3  112.49
5  114.67

最新更新