簡體   English   中英

使用 python 或 Matlab 將數據從 csv 文件轉換為 csv

[英]Transposing the data from csv file to csv using python or Matlab

我正在處理 csv 格式的具有四列和 912500 行的數據。 我需要將每列中的數據轉換為單獨的 csv 文件中的 365 列和 2500 行。 例如。

Col1 Col2 Col3 Col4

1 33 36 38

2 25 18 56

365 -4 -3 10

366 -11 20 35

367 12 18 27 . .

730 26 36 27。 .

. 912500 20 37 42

期望輸出

Col1  Col2 Col3  Col4 Col5 .....Col 365 

1 33 25................................-4

2 -11 12 ..................... 26

3

4………………

5……………… .

2500 ......................

請告訴我如何為此編寫腳本? 任何幫助將不勝感激。

嘗試按照評論中的建議使用 NumPy,但是,如果您想自己編寫代碼,您可以采用以下一種方法:

  • 您可以一次讀取一行文件

  • 使用逗號作為分隔符分割每一行

  • 丟棄“行數”(由於拆分操作而獲得的列表的第一個元素)。 您必須維護自己的行數。

  • 將剩余元素復制到另一個列表,直到您有 365 個元素(包括行數)
  • 將此列表作為 CSV 寫入輸出文件。 您可以使用 Python 的內置 CSV 編寫器 ( https://docs.python.org/2/library/csv.html )
  • 重復直到處理完整個輸入文件。

csv.reader將創建一個迭代器,逐行讀取 csv。 然后你可以將它輸入到itertools.chain ,它依次迭代每一行,輸出單獨的列。 現在您有了一個列流,您可以將它們分組為所需大小的新行。 有幾種方法可以重建這些行,我在示例中使用了itertools.groupby

import itertools
import csv

def groupby_count(iterable, count):
    counter = itertools.count()
    for _, grp in itertools.groupby(iterable, lambda _: next(counter)//count):
        yield tuple(grp)

def reshape_csv(in_filename, out_filename, colsize):
    with open(in_filename) as infile, open(out_filename, 'w') as outfile:
        reader = csv.reader(infile, delimiter=' ')
        writer = csv.writer(outfile, delimiter=' ')
        col_iter = itertools.chain.from_iterable(reader)
        writer.writerows(groupby_count(col_iter, colsize))

這是一個要測試的示例腳本。 不過,我使用了較少的列:

import os
infn = "intest.csv"
outfn = "outtest.csv"
orig_colsize = 4
new_colsize = 15

# test input file
with open(infn, "w") as infp:
    for i in range(32):
        infp.write(' '.join('c{0:02d}_{1:02d}'.format(i,j) for j in range(4)) + '\n')

# remove stale output file
try:
    os.remove(outfn)
except OSError:
    pass

# run it and print
reshape_csv(infn, outfn, new_colsize)
print('------- test output ----------')
print(open(outfn).read())

以下內容針對虛假數據文件進行了測試,它對我來說工作正常,但是 ymmv...請參閱內嵌注釋以了解工作原理

import csv

# we open the data file and put its content in data, that is a list of lists
with open('data.csv') as csvfile:
    data = [row for row in csv.reader(csvfile)]

# the following idiom transpose a list of lists
transpose = zip(*data)

# I use Python 3, hence zip is a generator and I have to throw away using next()
# the first element, i.e., the column of the row numbers
next(transpose)

# I enumerate transpose, obtaininig the data column by column    
for nc, column in enumerate(transpose):

    # I prepare for writing to a csv file
    with open('trans%d.csv'%nc, 'w') as outfile:
        writer = csv.writer(outfile)

        # here, we have an idiom, sort of..., please see
        #   http://stupidpythonideas.blogspot.it/2013/08/how-grouper-works.html
        # for the reason why what we enumerate are the rows of your output file
        for nr, row in enumerate(zip(*[iter(column)]*365)):
            writer.writerow([nr+1,*row])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM