繁体   English   中英

使用pandas.read_csv跳过多行

[英]Skip multiple rows using pandas.read_csv

我正在分块读取一个较大的csv文件,因为我没有足够的内存来存储。 我想读取其前10行(0至9行),跳过接下来的10行(10至19行),然后阅读接下来的10行(20至29行),再次跳过接下来的10行(30至39行) ),然后读取40到49之间的行,依此类推。 以下是我正在使用的代码:

#initializing n1 and n2 variable  
n1=1
n2=2
#reading data in chunks
for chunk in pd.read_csv('../input/train.csv',chunksize=10, dtype=dtypes,skiprows=list(range(  ((n1*10)+1), ((n2*10) +1) ))):
    sample_chunk=chunk
   #displaying the  sample_chunk
   print(sample_chunk)
   #incrementing n1
    n1=n1+2
   #incrementing n2
    n2=n2+2

但是,该代码不起作用,正如我认为的那样。 它仅跳过10到19的行(即:它读取0到9的行,跳过10到19,然后读取20到29,然后再次读取30到39,然后再次读取40到49,并继续读取所有行)。 请帮助我确定我在做什么错。

使用您的方法,您需要在初始化pd.read_csv时定义所有的skiprows

rowskips = [i for x in range(1,int(lengthOfFile/10),2) for i in range(x*10, (x+1)*10)]

lengthOfFile是文件的长度。

然后对于pd.read_csv

pd.read_csv('../input/train.csv',chunksize=10, dtype=dtypes,skiprows=rowskips)

从文档中:

skiprows : list-like, int or callable, optional

    Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file.

    If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be lambda x: x in [0, 2].

因此,您可以传递listintcallable

int >它跳过文件开头的给定行
list - >它跳过给出的行数list
callable - >它的计算结果与所述的行号callable ,然后决定跳过或没有。

您正在传递在启动时指定要跳过的行的list 您无法再次更新。 另一种方法可能是在行跳过中传递可调用的lamda x: x in rowskips它将评估行是否适合要跳过的条件。

码:

ro = list(range(0, lengthOfFile + 10, 10))
d = [j + 1 for i in range(1, len(ro), 2) for j in range(ro[i], ro[i + 1])]
# print(ro)
print(d)

pd.read_csv('../input/train.csv',chunksize=10, dtype=dtypes,skiprows=d)

例如:

lengthOfFile = 100
ro = list(range(0, lengthOfFile + 10, 10))
d = [j for i in range(1, len(ro), 2) for j in range(ro[i], ro[i + 1])]
print(d)

输出: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM