2017-03-23 9 views
1

私はこのサイトで新しくなっています。私は正しく質問をしてくれると願っています。1列のcsvデータを行数で複数の列に分割する

問題のあるガイダンスが必要です。

私はこのようなcsvファイルました:

| Column1| 
---------- 
abc 
def 
ghi 
12,34 
32,67 
jkl 
mno 
pqr 
28,34 
98,67 

(本当に悪いのファイルを)

そして私は、CSVのこの種に変換したい:

Something1 | Something2 | Something3 | Something4 | Something5 
--------------------------------------------------------------- 
    abc  | def  |  ghi | 12,34 | 32,67 
    jkl  | mno  |  pqr | 28,34 | 98,67 

あります15回の連続した行の合計15種類のデータがあり、新しいcsvファイルでは15回に分割する必要があります。

私が最初にやったのは、行数をカウントし、行数で新しいCSVファイルに分割する機能を持つbashスクリプトを作っていましたが、別の方法でPython私はこの種のゴミ箱のCSVファイルを取得する最後の時間になることはないので、(パンダとnumpy)またはPhP webservice(fopenと爆発的なデータまたはそのようなもの)があります...

しかし、始めるための指針。

何か助けていただければ幸いです。これについて

+0

なぜデータを区切るのにスペースと '|'文字を使用していますか? 'abd; def; ghi; 12,34; 32,67'も同様に動作しますか? – Adirio

+0

それは物事を分かりやすくするためのグラフィカルな例を作成しようとしましたが、反対の効果があるようです><、ofc結果はあなたが言うようにすべきです。投稿を編集する必要がありますか? –

+0

心配しないで、丁寧に質問してください – Adirio

答えて

0

このソリューションは、単に標準ライブラリを使用しています。

from csv import writer 

COLUMNS = 15 

with open("input_file.csv", "r") as input: 
    with open("output_file.csv", "w") as f: 
     output = writer(f, delimiter=";") 
     output.writerow(["Col {}".format(i+1) for i in xrange(COLUMNS)]) 
     buffer = [] 
     for row in input: 
      buffer.append(row) 
      if len(buffer) == COLUMNS: 
       output.writerow(buffer) 
       del buffer[:] 
     // You may want to check if there is something inside buffer at the end, for example if it has 23 rows buffer here will contain 8 elements and you may want to append them with: output.writerow(buffer) 
0

方法:

numCol = 15 

columns = [["col" + i] for i in xrange(numCol)] 

with open("...") as f: 
    for (i, line) in enumerate(f[1:]): 
     columns[i % numCol].append(line.rstrip()) 

csv = zip(*columns) 
0

パンダは、一般的にCSVデータに対処するための良い方法です。パンダのデータフレームに変換する方法の一例としては:入力と出力ファイルを想定し

f = open("yourfile", "r").readlines() # Your file 

# Split into groups 
from collections import defaultdict 
import itertools 
import pandas as pd 

cols = itertools.cycle(range(5)) # Use appropriate names for columns here 

# Add your data to your column names in a cycle 
d = defaultdict(list) 
for i in f[2:]: 
    d[next(cols)].append(i) 

print pd.DataFrame.from_dict(d) 



>>>  0 1 2  3  4 
0 abc def ghi 12,34 32,67 
1 jkl mno pqr 28,34 98,67 
0

は、あなたの質問に示すデータでのみ構成されています

try: 
    from itertools import izip 
except ImportError: # Python 3 
    izip = zip 

def grouper(n, iterable): 
    "s -> (s0,s1,...sn-1), (sn,sn+1,...s2n-1), (s2n,s2n+1,...s3n-1), ..." 
    return izip(*[iter(iterable)]*n) 

with open('trash.csv', 'r') as infile, open('pretty.csv', 'w') as outfile: 
    next(infile) # skip input header 
    outfile.write('Something1|Something2|Something3|Something4|Something5\n') # new header 
    for group in grouper(5, (line.strip() for line in infile)): 
     #print('|'.join(group)) 
     outfile.write('|'.join(group)+'\n') 
関連する問題