numpy初学者:使用numpy.savetxt编写数组 [英] numpy beginner: writing an array using numpy.savetxt

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

问题描述

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

I have a numpy histogram that I would like to output as a tab-delimited text file. My code is below:

targethist = np.histogram(targetlist, bins=ilist)
print targethist
np.savetxt('ChrI_dens.txt',targethist,delimiter='\t')

targetlist和ilist是一长串整数.我得到以下输出:

targetlist and ilist are long lists of integers. I get the following output:

(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

(array([0, 0, 0, ..., 0, 0, 0]), array([ 1, 10000, 20000, ..., 15060000, 15070000, 15072422])) Traceback (most recent call last): File "target_dens_np.py", line 62, in np.savetxt('ChrI_dens.txt',targethist,delimiter='\t') File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site-packages/numpy/lib/npyio.py", line 979, in savetxt fh.write(asbytes(format % tuple(row) + newline)) TypeError: float argument required, not numpy.ndarray

似乎已经创建了直方图数组,但是我在np.savetxt()行中做错了什么.我已经阅读了文档,但是不明白为什么此函数中的任何参数都将期望浮点数.我在哪里弄错了?

It seems that the histogram array has been created, but I have done something wrong in the np.savetxt() line. I have read the documentation, but don't understand why any of the arguments in this function would be expecting a float. Where have I gone wrong?

推荐答案

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

I think that the problem is that the second argument to savetxt must be "array-like". Your input is not "array-like". e.g.

print (len(targethist[0]))
print (len(targethist[1]))

注意长度不一样吗?如果长度相同,则numpy可以将其转换为单个2-D数组,一切都会好起来,但是它无法进行转换,因此会失败.

Notice the lengths aren't the same? If the lengths were the same, numpy could convert it to a single 2-D array and everything would be fine, but it can't do the conversion so it fails.

这有效

np.savetxt('stuff.dat',(targethist[0],targethist[1][1:]),delimiter='\t')

但是我已经删掉了您的数据;).您需要确定要解决的问题.

But I've truncated your data ;). You'll need to decide what you want to do to work around this one.

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

I must admit, the error message here is quite cryptic.

这篇关于numpy初学者:使用numpy.savetxt编写数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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