2015-01-25 4 views
0

데이터의 하위 집합을 포함하는 다른 형식의 CSV를 생성하기 위해 4GB의 RAM 만있는 컴퓨터에서 큰 (2GB) csv 파일을 처리하려고합니다 (묻지 않음). 일부 처리가 필요합니다. 파일을 읽고 출력을 위해 필요한 데이터에 대해 나중에 쿼리하는 HDFstore를 만듭니다. 용어를 사용하여 저장소에서 데이터를 검색 할 수 없다는 것을 제외하고 모두 작동합니다. PLOT이 열 이름이 아니라는 오류 메시지가 다시 나타납니다. 개별 변수는 괜찮아 보이고 저장소는 내가 어디에서 오류인지 알 수 없기를 기대합니다. (nb 팬더 v14 및 numpy1.9.0). 매우 새로운이 너무 clunky 코드에 대한 사과. 여기에 도달하기 위해 다니지을 통해 싸움을하고자하는 유사 큰 .CSV 파일 및/프로세스 데이터를 검색하는 다양한 방법을 처리하여 잠기 게되는 사람들을 위해pandas HDF select가 열 이름을 인식하지 못함

#wibble wobble -*- coding: utf-8 -*- 
# short version 
def filesport(): 
    import pandas as pd 
    import numpy as np 
    from pandas.io.pytables import Term 

    Location = r"CL_short.csv" 
    store = pd.HDFStore('blarg.h5') 

    maxlines = sum(1 for line in open (Location)) 
    print maxlines 
#set chunk small for test file 
    chunky=4 
    plotty =pd.DataFrame(columns=['PLOT']) 
    dfdum=pd.DataFrame(columns=['PLOT', 'mDate', 'D100']) 

#read file in chunks to avoid RAM blowing up  
    bucket = pd.read_csv(Location, iterator=True, chunksize=chunky, usecols= ['PLOT','mDate','D100']) 

    for chunk in bucket: 
     store.append('wibble', chunk, format='table', data_columns=['PLOT','mDate','D100'], ignore_index=True) 

#retrieve plot numbers and select unique items 
    plotty = store.select('wibble', "columns = ['PLOT']") 
    plotty.drop_duplicates(inplace=True) 

#iterate through unique plots to retrieve data and put in dataframe for output 
    for index, row in plotty.iterrows(): 
     dfdum = store.select('wibble', [Term('PLOT', '=', plotty.iloc[index]['PLOT'])]) 
#process dfdum for output to new csv 

    print("successful completion") 
filesport() 
+0

내가 답변 해 드리겠습니다 내 자신의 질문을 찾을 희망을 다른 웹의, 외로운 구석에 문제가 발생하고이 어둠 속에서 자신을 발견하면 . 문제는 용어는 문자열이어야하고 용어의 숫자 부분은 문자열이 아닌 숫자 변수입니다. 나는 term() 부분 내에서 작동하도록 str 함수를 얻을 수는 없지만,이 작업은 plotty.iterrows()의 행 인덱스에 적용됩니다. condition = 'PLOT ='+ str (plotty.iloc [index] [ 'PLOT' ]) dfdum = store.select ('wibble', [Term (condition)]). dfdum = store.select ('wibble', [기간 (조건)])에 대한 – zarquon

+0

의 경우 plotty.iterrows ()의 행에 대한 조건 : 'PLOT ='+ str (plotty.iloc [인덱스] [ ' ]) – zarquon

답변

0

최종 목록. 가장 큰 문제는 pytables 용어의 sytax를 얻는 것이 었습니다. 몇 가지 예를 들자면 'A> 20'등을 사용할 수 있음을 나타내었지만 이것은 절대로 효과가 없었습니다. 용어 쿼리를 포함하는 문자열 조건을 설정했는데 이것이 작동했습니다 (문서 TBF에 있음).
또한 HDF를 쿼리하여 상점에서 직접 가져온 고유 항목을 목록에서 직접 검색 할 수 있습니다.이 항목은 정렬 및 플롯별로 데이터 플롯 검색을 반복 할 수 있습니다. 필자는 최종 CSV 파일에 플롯을 작성한 다음 모든 D100 데이터를 날짜 순서대로 원했기 때문에 결국에는 피벗을 원했습니다.
청크로 csv 파일을 읽는 것은 저장소에서 검색된 각 플롯에 헤더가 있음을 의미하며 최종 CSV에 기록됩니다. 여기에 표시된 것보다 하나의 헤더 만 쓰는보다 우아한 방법이있을 것입니다.
데이터를 처리하고 최종 CSV 파일을 생성하는 데 약 2 시간이 걸립니다 (초기 파일 2GB, 30 백만 회선, 100,000+ 고유 플롯 데이터, 4GB RAM, 32 비트 실행). 2.5GB의 RAM을 사용할 수 있음).
행운을 빌어 요 당신은 유사한 문제가, 그리고 당신이 경우 사람이 유용

#wibble wobble -*- coding: utf-8 -*- 

def filesport(): 
    import pandas as pd 
    import numpy as np 
    from pandas.io.pytables import Term 

    print (pd.__version__) 
    print (np.__version__) 

    Location = r"conliq_med.csv" 
    store = pd.HDFStore('blarg.h5') 

    maxlines = sum(1 for line in open (Location)) 
    print maxlines 
    chunky=100000 

#read file in chunks to avoid RAM blowing up select only needed columns 
    bucket = pd.read_csv(Location, iterator=True, chunksize=chunky, usecols= ['PLOT','mDate','D100']) 

    for chunk in bucket: 
     store.append('wibble', chunk, format='table', data_columns=['PLOT','mDate','D100'], ignore_index=True) 

#retrieve unique plots and sort 
    plotty = store.select_column('wibble', 'PLOT').unique() 
    plotty.sort() 
#set flag for writing file header 
    i=0 

#iterate through unique plots to retrieve data and put in dataframe for output 
    for item in plotty: 
     condition = 'PLOT =' + str(item) 
     dfdum = store.select('wibble', [Term(condition)]) 
     dfdum["mDate"]= pd.to_datetime(dfdum["mDate"], dayfirst=True) 
     dfdum.sort(columns=["PLOT", "mDate"], inplace=True) 
     dfdum["mDate"] = dfdum["mDate"].map(lambda x: x.strftime("%Y - %m")) 
     dfdum=dfdum.pivot("PLOT", "mDate", "D100") 

#only print one header to file 
     if i ==0: 
      dfdum.to_csv("CL_OP.csv", mode='a') 
      i=1 
     else: 
      dfdum.to_csv("CL_OP.csv", mode='a', header=False) 

    print("successful completion") 

filesport() 
관련 문제