读入大表文件,但使用pandas只保留一小部分行

2024-04-27 16:57:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

读取文件,但这会遇到read_table命令的内存问题。有没有一种更快更节省内存的方法?谢谢。你知道吗


Tags: 文件数据方法内存txt距离列表read
1条回答
网友
1楼 · 发布于 2024-04-27 16:57:13

需要^{}参数如果需要筛选列和skiprows对于筛选行,必须指定哪些列必须由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'默认为^{}

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

使用^{}的更一般的解决方案:

#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

相关问题 更多 >