numpy.loadtxt文件对于一个或多个输入行

2024-04-24 10:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据文件,可能是一行或多行。我用numpy.loadtxt来读它。它的功能是使单行数据成为标量。这是有问题的,因为我想在读入后使用循环。请参见下面的示例

$ cat file1
1
$ cat file2
1
2
$ python --version
Python 2.7.6
$ python 
$ python temp.py 
1.0
2.0
Traceback (most recent call last):
  File "temp.py", line 9, in <module>
    for x in data1:
TypeError: iteration over a 0-d array

代码

^{pr2}$

我也尝试了相关问题的解决方案:numpy loadtxt single line/row as list但是我没有让它起作用

我补充道

data1 = data1 if usi.shape else [data1]

但是

$ python temp.py 
Traceback (most recent call last):
  File "temp.py", line 7, in <module>
    data1 = data1 if usi.shape else [data1]
NameError: name 'usi' is not defined

我也尝试了import usi,但我的系统上没有安装这个功能,对于这样一个简单的任务来说似乎有点过头了。在

我做错什么了?我觉得解决方案很简单,但我找不到http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html的提示


Tags: inpy功能numpymostlinecalltemp
2条回答

尝试:

data1=numpy.loadtxt ( 'file1', unpack=True, ndmin = 1)

可以调用^{}将其提升到0-d对象之外:

>>> np.loadtxt("file1.txt")
array(1.0)
>>> np.atleast_1d(np.loadtxt("file1.txt"))
array([ 1.])

也可以安全地应用到第二个数组,因为它不会做任何事情:

^{pr2}$

另请参见np.atleast_2d。在

相关问题 更多 >