Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python跳过文件中的某些行_Python_Pandas - Fatal编程技术网

使用Python跳过文件中的某些行

使用Python跳过文件中的某些行,python,pandas,Python,Pandas,假设我有这样一个文本文件: A 12 16 91 A 22 56 31 A 17 25 22 B 34,543,683,123 34 A 19 27 32 B 45,48,113,523 64 A 11 24 72 C asd,asd,qwe ewr 123 使用csv_read,我可以: from_csv = pd.read_csv('test.txt', sep=' ', header=None, names=['a','s','d','f']) from_csv.head() 如果不存

假设我有这样一个文本文件:

A 12 16 91
A 22 56 31
A 17 25 22
B 34,543,683,123 34
A 19 27 32
B 45,48,113,523 64
A 11 24 72
C asd,asd,qwe ewr 123
使用csv_read,我可以:

from_csv = pd.read_csv('test.txt', sep=' ', header=None, names=['a','s','d','f'])
from_csv.head()
如果不存在以
B
C
开头的行,则该选项可以正常工作


我如何告诉read_csv只读以
A开始的行?

您可以自己进行筛选:

import pandas as pd
import csv


def read_only_csv(fle, keep, col,sep=",", **kwargs):
    with open(fle) as f:
        return pd.DataFrame.from_records((r for r in csv.reader(f, delimiter=sep) if r[col] == keep),
                                       **kwargs)



df = read_only_csv("test.txt", "A", 0, sep=" ",columns=['a', 's', 'd', 'f'])
这将给你:

  a   s   d   f
0  A  12  16  91
1  A  22  56  31
2  A  17  25  22
3  A  19  27  32
4  A  11  24  7
对于一个大约有80k行的文件,使用read_csv然后过滤速度更快,唯一的优势是不会占用那么多内存

In [24]: %%timeit     
df = pd.read_csv('out.txt', sep=' ', header=None, names=['a','s','d','f'])
df = df[df["a"] == "A"]
   ....: 
10 loops, best of 3: 31.8 ms per loop

In [25]: timeit read_only_csv("out.txt", "A", 0, sep=" ", columns=['a', 's', 'd', 'f'])

10 loops, best of 3: 41.1 ms per loop

我同意自己过滤的另一种选择,但我认为如果您将文件分块读取,过滤您想要保留的行,然后使用一个Pandas阅读器(而不是每行创建一个阅读器),速度会更快:

然后可以将返回的对象像文件一样传递给熊猫

from_csv = pd.read_csv(read_buffered('test.txt','A'), 
     sep=' ', header=None, names=['a','s','d','f'])
from_csv.head()
在我的测试中,这大约是公认解决方案的两倍(但这可能取决于筛选出的行的分数,以及是否可以在内存中容纳两个数据副本):


不,您必须作为后处理步骤进行筛选,因此
df[df['a']='a']你想跳过从B开始的行还是从A?@ PadraicCunningham开始的所有行最好跳过除<代码> A/<代码>之外的所有行,还应该考虑在这个步骤中的过滤或在后处理步骤中的有用性和性能是否更好。在加载之前检查csv中的每一行会很慢,而不仅仅是加载然后根据文件大小进行过滤
from_csv = pd.read_csv(read_buffered('test.txt','A'), 
     sep=' ', header=None, names=['a','s','d','f'])
from_csv.head()
In [128]: timeit pd.read_csv(read_buffered("test.txt","A"), sep=' ', header=None, names=['a','s','d','f'])
10 loops, best of 3: 22 ms per loop

In [129]: timeit read_only_csv("test.txt", "A", 0, sep=" ", columns=['a', 's', 'd', 'f'])                     
10 loops, best of 3: 45.7 ms per loop