将具有numpy数组的字典写入.csv [英] Write dictionary with numpy arrays to .csv

查看:107
本文介绍了将具有numpy数组的字典写入.csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将结果文件写入.csv.我准备了一个简单的测试示例.

I want to write resultfiles to .csv. I prepared a simple test example.

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}

获得这样的结果文件将是很棒的:

It would be great to get a result file like this:

有没有一种简单的方法可以建议您?

Is there a simple way that you can recomment?

推荐答案

您可以在单独的数据结构中收集标题和行,然后使用csv模块将所有内容写入Excel工作表.另外,data字典需要转换为OrderedDict才能保持顺序.

You can collect headers and rows in separate data structures and then use csv module to write everything to an excel sheet. Also, the data dict needs to be converted to OrderedDict to maintain order of sequence.

源代码

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

这篇关于将具有numpy数组的字典写入.csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆