[英]Writing a python Dictionary to a CSV file with keys as column headers
I'm trying to write the elements in my dictionary into a text file where each key would be a column. 我正在尝试将字典中的元素写入文本文件,其中每个键都是一列。 Currently have I something that looks like 目前我的东西看起来像
import csv
import numpy as np
data1 = np.arange(10)
data2 = np.arange(10)*2
data3 = np.arange(10)*3
writefile = '../Desktop/data.txt'
datadict = {}
datadict['data1'] = data1
datadict['data2'] = data2
datadict['data3'] = data3
f = open( writefile, 'w' )
fieldnames = ['data1','data2', 'data3']
data = csv.DictWriter(writefile, fieldnames, restval='', extrasaction='ignore', dialect='excel')
f.close()
but it gives me the error "argument 1 must have a "write" method". 但它给了我错误“参数1必须有一个”写“方法”。 I'm not sure what that means. 我不确定这意味着什么。 I'm also worried about the dialect = 'excel', but I'm not sure what else to put. 我也担心方言='excel',但我不确定还能放什么。 In the end I'd like a file that has something looking like: 最后,我想要一个看起来像这样的文件:
Thanks 谢谢
No need to use DictWriter here at all: 这里根本不需要使用DictWriter:
import csv
import numpy as np
data1 = np.arange(10)
data2 = np.arange(10)*2
data3 = np.arange(10)*3
writefile = '../test.csv'
fieldnames = ['data1','data2', 'data3']
with open( writefile, 'w' ) as f:
writer = csv.writer(f)
writer.writerow(fieldnames)
writer.writerows(zip(data1, data2, data3))
You should pass the file-like object as the first argument to the DictWriter
constructor. 您应该将类文件对象作为第一个参数传递给DictWriter
构造函数。
datalist = [{'data1': d1, 'data2': d2, 'data3': d3} for d1, d2, d3 in zip(data1, data2, data3)]
...
f = open(writefile, 'w')
...
writer = csv.DictWriter(f, ...)
for i in xrange(10):
writer.writerow(datalist[i])
f.close()
More simple analogic case: 更简单的类比案例:
with open(writefile, 'w') as f:
writer = csv.writer(f)
for row in zip(data1, data2, data3):
writer.writerow(row)
If you're doing the kind of data analysis it looks like you might be doing here, the best bet might be to get into pandas
, Python's dedicated data analysis library. 如果您正在进行这种数据分析,看起来您可能正在这里进行,最好的选择可能是进入pandas
,Python的专用数据分析库。
Here's an example which does what you want: 这是一个做你想要的例子:
import pandas as pd
import numpy as np
data1 = np.arange(10)
data2 = np.arange(10)*2
data3 = np.arange(10)*3
df = pd.DataFrame(zip(data1, data2, data3), columns=['data1', 'data2', 'data3'])
df.to_csv('myfile.csv')
Pretty neat I'd say. 我说的很漂亮。 Additionally, you can now do all sorts of unimaginable things with your data. 此外,你现在可以做的所有 各种各样的难以想象的 事情与您的数据。
You can also make a DataFrame
from an existing dictionary: 您还可以从现有字典中创建DataFrame
:
In [115]: a_dict = {'foo':[1,2,3], 'bar':[4,5,6], 'baz':[7,8,9]}
In [116]: pd.DataFrame(a_dict)
Out[116]:
bar baz foo
0 4 7 1
1 5 8 2
2 6 9 3
Try this: 尝试这个:
import csv
import numpy as np
data1 = np.arange(10)
data2 = np.arange(10)*2
data3 = np.arange(10)*3
writefile = '../Desktop/data.txt'
datadictlist = [{'data1': data1[i], 'data2': data2[i], 'data3': data3[i]} for i in xrange(10)]
f = open( writefile, 'w' )
fieldnames = ['data1','data2', 'data3']
writer = csv.DictWriter(f, fieldnames, restval='', extrasaction='ignore', dialect='excel')
writer.writerows(datadictlist)
f.close()
把'a +'代替'w'
f = open( writefile, 'a+' )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.