2017-10-11 89 views
1

我想將結果文件寫入.csv。我準備了一個簡單的測試例子。使用numpy數組將字典寫入.csv

import numpy as np 
data = {} 
testdata = np.array([1,2,3,4,5]) 

data['set1'] = {'a': testdata, 'b': testdata, 'c': testdata} 
data['set2'] = {'a2': testdata, 'b2': testdata, 'c2': testdata} 
data['set3'] = {'a3': testdata, 'b3': testdata, 'c3': testdata} 

這將是巨大的,得到的結果文件是這樣的:

enter image description here

是否有可以電子書籍的簡單方法?

+0

https://docs.python.org/2/library/csv.html#csv.writer你試過用' csv'模塊?嘗試一些例子,你應該能夠弄清楚。 – sam

回答

3

您可以收集單獨數據結構中的標題和行,然後使用csv模塊將所有內容寫入Excel表。此外,data字典需要轉換爲OrderedDict維護順序的順序。

源碼

import numpy as np 
import csv 
from collections import OrderedDict 
from itertools import chain 


data = {} 

testdata = np.array([1,2,3,4,5]) 
data = OrderedDict(data) 


a = {'a': testdata, 'b': testdata, 'c': testdata} 
b = {'a2': testdata, 'b2': testdata, 'c2': testdata} 
c = {'a3': testdata, 'b3': testdata, 'c3': testdata} 

#covert inner dict to OrderedDict 
data['set1'] = OrderedDict(sorted(a.items(), key=lambda x:x[0])) 
data['set2'] = OrderedDict(sorted(b.items(), key=lambda x:x[0])) 
data['set3'] = OrderedDict(sorted(c.items(), key=lambda x:x[0])) 

#collect second header 
header2 = [data.get(k).keys() for k in data.keys()] 

#get number of repetations for header1 
header1_size = len(header2[0]) 

#get header1 
header1 = sorted((data.keys())*header1_size) 

#flatten list of list of header2 
header2 = list(chain.from_iterable(header2)) 

#get rows from data dict 
rows = zip(*[v2 for k1,v1 in data.items() for k2,v2 in v1.items() ]) 

#write header1,header2 and rows to excel /csv 
with open('csvfile.csv','wb') as ofile:    
    wr = csv.writer(ofile, dialect='excel') 
    wr.writerow(header1) 
    wr.writerow(header2) 
    wr.writerows(rows) 

csvfile
enter image description here