Python - 将分箱数据保存到文本文件

3
我想要将一些柱状图数据保存在CSV文件中。这是我写的代码:
ExportName_csv = 'ExportData/' + FileName + '.csv'
freq, bins = np.histogram(ValList,bins)
np.savetxt(ExportName_csv, izip(freq, bins), delimiter="\t")

对于每个箱子,我想保存箱子的值和相应的计数 freqExportName_csv 中。我希望不同箱子的值在不同行中;在每一行中,值用逗号分隔。
使用当前代码会出现错误 IndexError: tuple index out of range。您建议怎么做?
完整的回溯信息如下:
np.savetxt(ExportName_csv, izip(freq, bins), delimiter="\t") 
   File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/nump‌​y/lib/npyio.py", line 976, in savetxt ncol = X.shape[1] 
IndexError: tuple index out of range

提供示例的“ValList”和完整的回溯信息将有助于更快地回答您的问题。 - alko
请注意,逗号是“,”,制表符是“\t”。 - alko
以下是完整的回溯信息: np.savetxt(ExportName_csv, izip(freq, bins), delimiter="\t") File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/npyio.py", line 976, in savetxt ncol = X.shape[1] IndexError: tuple index out of range - albus_c
这里您可以找到使用json.dump(ValList, f)打印的ValList值的示例:http://cl.ly/text/2n420p2o2Y3S - albus_c
1个回答

3

首先,逗号是','而不是\t

其次,在IT技术中应当使用zip而不是izip

>>> data = zip(*np.histogram(ValList,bins))
>>> np.savetxt('test.txt', data, delimeter=',')

2
注意,bins 的长度始终比 freq 长一个,因此 zip 会剪切掉最后一个箱子边缘。如果箱子等距离分布,则不会丢失任何信息,但您应该意识到这一点。 - askewchan
@askewchan 如果其他用户打开CSV文件,他们将不知道最后一个bin被切断了。因此,除非您还提供一些标题,否则创建者应该小心。 - Jelmer Mulder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接