简体   繁体   English

pandas read_csv-从某一行开始跳过每隔一行

[英]pandas read_csv - Skipping every other row starting from a certain row

I have a huge .csv file (over 1 million rows), that I am trying to parse using the pandas read_csv function. 我有一个巨大的.csv文件(超过一百万行),我正在尝试使用pandas read_csv函数进行解析。 The file is very large because it is measurement data from a sensor with very high sampling rate, and I want to take downsampled segments from it. 该文件非常大,因为它是来自具有很高采样率的传感器的测量数据,我想从中获取降采样的片段。 I tried implementing it with a lambda function and the skiprows and nrows parameter. 我尝试用lambda函数以及skiprowsnrows参数实现它。 What my code currently does is, it just reads the same segment over and over again. 我的代码当前所做的是,它一次又一次地读取同一段。

segment_amt = 20 # How many segments we want from a individual measurement file
segment_length = 5 # Segment length in seconds
segment_length_idx = fs * segment_length # Segmenth length in indices
segment_skip_length = 10 # How many seconds between segments
segment_skip_idx = fs * segment_skip_length # The amount of indices to skip between each segment
downsampling = 2 # Factor of downsampling

idx = start_idx
for i in range(segment_amt):

    cond = lambda x: (x+idx) % downsampling != 0
    data = pd.read_csv(filename, skiprows=cond, nrows = segment_length_idx/downsampling,
           usecols=[z_component_idx],names=["z"],engine='python')
    M1_df = M1_df.append(data.T)
    idx += segment_skip_idx

This results in something like this . 这导致像这样 I assume the behaviour is due to the lambda function, but I don't know how to fix it, so that it changes the starting row each time based on idx (this is what I thought it would do currently). 我认为该行为是由于lambda函数引起的,但我不知道如何解决它,因此它每次都基于idx更改起始行(这是我目前认为的做法)。

Your cond lambda is wrong. 您的cond lambda错误。 You want to skip rows if x < idx or x % downsampling != 0 . 如果x < idxx % downsampling != 0 x < idx跳过行。 Just write it that way: 只是这样写:

cond = x < idx or x % downsampling != 0

But you should also consider passing header = False to avoid processing the first line of each segment as a header. 但是,您还应该考虑传递header = False以避免将每个段的第一行作为标题处理。

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

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