2012-11-30 4 views

답변

82

CSV 파일을 팬더 개체에로드하기 전에 행을 필터링하는 옵션이 없습니다.

파일을로드 한 다음 df[df['field'] > constant]을 사용하여 필터링하거나 매우 큰 파일이 있고 메모리가 부족하다는 것에 대한 걱정이있는 경우 반복기를 사용하여 파일의 덩어리를 연결할 때 필터를 적용 할 수 있습니다. 예 :

iter_csv = pandas.read_csv('file.csv', iterator=True, chunksize=1000) 
df = pd.concat([chunk[chunk['field'] > constant] for chunk in iter_csv]) 

사용 가능한 메모리에 맞게 chunksize을 다양하게 지정할 수 있습니다. 자세한 내용은 here을 참조하십시오.

+0

'chunk ['filed 'constant>'에 대해 2 개의 상수 값 사이에 샌드위치 넣을 수 있습니까? 예 : constant1> 청크 [ 'field']> constant2. 또는 '범위 내'를 사용할 수 있습니까? – weefwefwqg3

4

read_csv의 컨텍스트 내에서 직접 작업 할 수있는 방법을 찾지 못했습니다. 있다는

filtered = df[(df['timestamp'] > targettime)] 

이 DF의 모든 행을 선택한다 (가정 DF 어떤 DataFrame 같은 read_csv 호출의 결과로한다 : 그러나, read_csv 부울 벡터 df[bool_vec]하여 행을 선택하여 필터링 할 수 DataFrame를 반환 적어도 timestamp 열의 값이 targettime의 값보다 큰 datetime 열 timestamp이 있어야합니다. Similar question.

0

당신이 리눅스에 있다면 grep을 사용할 수 있습니다.

# to import either on Python2 or Python3 
import pandas as pd 
from time import time # not needed just for timing 
try: 
    from StringIO import StringIO 
except ImportError: 
    from io import StringIO 


def zgrep_data(f, string): 
    '''grep multiple items f is filepath, string is what you are filtering for''' 

    grep = 'grep' # change to zgrep for gzipped files 
    print('{} for {} from {}'.format(grep,string,f)) 
    start_time = time() 
    if string == '': 
     out = subprocess.check_output([grep, string, f]) 
     grep_data = StringIO(out) 
     data = pd.read_csv(grep_data, sep=',', header=0) 

    else: 
     # read only the first row to get the columns. May need to change depending on 
     # how the data is stored 
     columns = pd.read_csv(f, sep=',', nrows=1, header=None).values.tolist()[0]  

     out = subprocess.check_output([grep, string, f]) 
     grep_data = StringIO(out) 

     data = pd.read_csv(grep_data, sep=',', names=columns, header=None) 

    print('{} finished for {} - {} seconds'.format(grep,f,time()-start_time)) 
    return data 
관련 문제