2016-09-08 4 views
2

저는 파이썬 초보자입니다. 파이썬에서 CSV 파일을 조작하는 데 도움이 필요합니다. 데이터 집합의 각 행에 대해 슬라이딩 창 메커니즘을 수행하려고합니다. 예는파이썬에서 CSV 파일 (슬라이딩 윈도우)

데이터 세트가 ObjectsArray 목록을 사용하여 내가 이것을 할 수

timestamp | temperature-2 | temperature-1 |temperature-0 | windspeed-2 | windspeed-1 | windspeed-0 
965070000 9.61883 9.47203 9.31125 60.262 60.1664 60.0145 
965070900 9.47203 9.31125 9.13649 60.1664 60.0145 59.8064 

등이

timestamp | temperature | windspeed 
965068200 9.61883 60.262 
965069100 9.47203 60.1664 
965070000 9.31125 60.0145 
965070900 9.13649 59.8064 

및 사용자 지정 창 크기가 3 인 경우, 결과는해야 뭔가가있는 경우 CSV를 읽고 변환 된 데이터 세트가 포함 된 새 CSV를 생성합니다. 가 여기에 내가 파이썬에서이 작업을 수행하는 데 필요한 코드 http://pastebin.com/cQnTBg8d #researh

이며,이 문제를 해결하는 데 도움이 바랍니다.

감사합니다

+0

당신이 [CSV (https://docs.python.org/3/library/csv.html) 모듈을 살펴 있었나요 (주석 참조) 아직? – janbrohl

+0

이것은 실제 csv처럼 보이지 않으므로 문자열 메소드를 사용하는 것이 더 쉬울 수 있습니다. – janbrohl

+0

은 (는) 당신의 CSV가 큽니까? 기억에 남을 수 있습니까? –

답변

0

이 답변 파이썬 3.x를를 사용하는 가정 - 파이썬은 약간의 변화는 데이터 형식에 대한

에서 (일부 명백한 장소 주석) 필요 2.x에서 문제는,이 파이썬에서 시작하는 포인트가 될 수있다 : 실제로

import collections 

def slide(infile,outfile,window_size): 
    queue=collections.deque(maxlen=window_size) 
    line=infile.readline() 
    headers=[s.strip() for s in line.split("|")] 
    row=[headers[0]] 
    for h in headers[1:] 
     for i in reversed(range(window_size)): 
      row.append("%s-%i"%(h,i)) 
    outfile.write(" | ".join(row)) 
    outfile.write("\n") 
    for line in infile: 
     queue.append(line.split()) 
     if len(queue)==window_size: 
      row=[queue[-1][0]] 
      for j in range(1,len(headers)): 
       for old in queue: 
        row.append(old[j]) 
      outfile.write("\t".join(row)) 
      outfile.write("\n") 

ws=3 
with open("infile.csv","r") as inf: 
    with open("outfile.csv","w") as outf: 
     slide(inf,outf,ws) 

이 코드는 모든 윈도우의 입력 행을 유지하기 위해 큐를 사용하는 방법에 대한 그 밖의 모든 것은 텍스트 - 목록 - 투 - 텍스트입니다. 실제 CSV 데이터로

,

import csv 
import collections 

def slide(infile,outfile,window_size): 
    r=csv.reader(infile) 
    w=csv.writer(outfile) 
    queue=collections.deque(maxlen=window_size) 
    headers=next(r) # r.next() on python 2 
    l=[headers[0]] 
    for h in headers[1:] 
     for i in reversed(range(window_size)): 
      l.append("%s-%i"%(h,i)) 
    w.writerow(l) 
    hrange=range(1,len(headers)) 
    for row in r: 
     queue.append(row) 
     if len(queue)==window_size: 
      l=[queue[-1][0]] 
      for j in hrange: 
       for old in queue: 
        l.append(old[j]) 
      w.writerow(l) 

ws=3 
with open("infile.csv","r") as inf: # rb and no newline param on python 2 
    with open("outfile.csv","w") as outf: # wb and no newline param on python 2 
     slide(inf,outf,ws) 
+0

@janbrohl 님의 지원에 감사드립니다.이 줄에 오류가 발생했습니다. infile.readline(). strip(). strip ("*"). split ("|")에서 s의 headers = [s.strip() 지금 질문을 편집하십시오 언급하십시오. –

+0

이에 따라 변경됨 – janbrohl

+0

@janbrohl에 감사드립니다. 일부 오류로 인해 컴파일 할 수 없습니다. 너무 고칠 수 있니? https://i.imgsafe.org/14dea045e4.png –

관련 문제