2016-09-08 3 views
2

私はPythonの初心者です。私はPythonでcsvファイルを操作するための助けが必要です。 私は、データセットの各行に対してスライディングウィンドウメカニズムを実行しようとしています。例えばPythonでのCSVファイル(スライディングウィンドウ)

私はObjectsArrayのリストを使用してこれを行うことができ、データセットは、この

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

であり、ユーザがウィンドウサイズが3で指定した場合、結果は

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 

のようなものであるべき場合CSVを読み込み、変換されたデータセットを含む新しいCSVを生成します。 ここにコードがあります http://pastebin.com/cQnTBg8d #researh

私はこれをPythonで行う必要があります。

は、この答えは、あなたがPythonの3.xを使用していると仮定し、あなたに

+0

あなたは[CSV](https://docs.python.org/3/library/csv.html)モジュールを見たことがあり、まだですか? – janbrohl

+0

これは実際には実際のCSVのようには見えないので、文字列メソッドを使用する方が簡単です。 – janbrohl

+0

はあなたのcsvビッグですか?それは記憶に保持できますか? –

答えて

0

をありがとう - (いくつかの明白な場所がコメントしている)いくつかの変更が必要とされているから2.xのPython用

のデータ形式について質問、これはPythonで出発点のようになります。

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 –

関連する問題