I have a data file with only one line like:
1.2 2.1 3.2
我使用numpy版本1.3.0的loadtxt进行加载。
a,b,c = loadtxt("data.dat", usecols(0,1,2), unpack=True)
输出结果是浮点数而不是类数组。
a = 1.2
我预计这应该是:
a = array([1.2])
如果我读取一个有多行的文件,它是可以工作的。
只需使用numpy的内置loadtxt参数ndmin即可。
a,b,c=np.loadtxt('data.dat',ndmin=2,unpack=True)
输出
a=[1.2]
#note the reshape function to transform the shape
a,b,c = loadtxt("text.txt").reshape((-1,1))
如果你需要它在多维数组上正常工作,并在读取一维数组时保持一维,我认为最好的方法是使用loadtxt正常读取,然后在第二阶段重塑数组,如果它们是纯数字,则将其转换为单一维度。
a,b,c = loadtxt("text.txt",unpack=True)
for e in [a,b,c]
e.reshape(e.shape if e.shape else (-1,))
不使用reshape的简单方法是显式地将列表转换类型
a,b,c = loadtxt("data.dat", usecols(0,1,2), unpack=True)
a,b,c = (a,b,c) if usi.shape else ([a], [b], [c])
这比reshape快!
ndim
是在numpy 1.6中实现的,而OP使用的不是这个版本。 - FabienP