numpy 初学者:使用 numpy.savetxt 编写数组

pan*_*Seq 4 python csv numpy histogram

我有一个 numpy 直方图,我想将其输出为制表符分隔的文本文件。我的代码如下:

targethist = np.histogram(targetlist, bins=ilist)
print targethist
np.savetxt('ChrI_dens.txt',targethist,delimiter='\t')
Run Code Online (Sandbox Code Playgroud)

targetlist 和 ilist 是长整数列表。我得到以下输出:

(array([0, 0, 0, ..., 0, 0, 0]), array([ 1, 10000, 20000, ..., 15060000, 15070000, 15072422])) 回溯(最近一次调用) :文件“target_dens_np.py”,第 62 行,在 np.savetxt('ChrI_dens.txt',targethist,delimiter='\t') 文件“/Library/Frameworks/Python.framework/Versions/7.3/lib/python2. 7/site-packages/numpy/lib/npyio.py”,第 979 行,在 savetxt fh.write(asbytes(format % tuple(row) + newline)) 中 TypeError:需要 float 参数,而不是 numpy.ndarray

似乎直方图数组已创建,但我在 np.savetxt() 行中做错了一些事情。我已阅读文档,但不明白为什么此函数中的任何参数都需要浮点数。我哪里出错了?

mgi*_*son 5

我认为问题在于第二个参数savetxt必须是“类似数组”。您的输入不是“类似数组”。例如

print (len(targethist[0]))
print (len(targethist[1]))
Run Code Online (Sandbox Code Playgroud)

注意到长度不一样了吗?如果长度相同,numpy 可以将其转换为单个二维数组,一切都会很好,但它无法进行转换,因此会失败。

这有效

np.savetxt('stuff.dat',(targethist[0],targethist[1][1:]),delimiter='\t')
Run Code Online (Sandbox Code Playgroud)

但我已经截断了你的数据;)。您需要决定要采取什么措施来解决这个问题。

我必须承认,这里的错误消息非常神秘。