当fname
是一个空文件时,有没有办法让numpy.loadtxt(fname, ..)
创建一个形状为(0, ncol)
的数组,其中ncol
是我指定的一个增强器?
例如,如果我运行以下脚本,
#!/usr/bin/python3
import numpy as np
aa = np.loadtxt('fanmab.dat', ndmin=2)
print('aa.shape=', aa.shape)
ae = np.loadtxt('fempty.dat', ndmin=2)
#ae = np.loadtxt('fempty.dat', ndmin=2, usecols=(0,1,2,3))
print('ae.shape=', ae.shape)
有了这些文件,fanmab.dat
# This is fanmab.dat
0.1234 0.56 0.78 0.90
1.1234 1.56 1.78 1.90
2.1234 2.56 2.78 2.90
和fempty.dat
# This is an empty file
我在python中看到了以下stdout
$ ./main.py
aa.shape= (3, 4)
/usr/lib/python3/dist-packages/numpy/lib/npyio.py:816: UserWarning: loadtxt: Empty input file: "fempty.dat"
warnings.warn('loadtxt: Empty input file: "%s"' % fname)
ae.shape= (0, 1)
当只有ndmin=2
行需要读入时,第二个维度的长度似乎会自动设置为1
。设置usecols
似乎没有什么帮助。
我需要做下面这样的事情吗?
if ae.shape[0]==0:
ae.reshape((0,ncol))
发布于 2017-06-15 04:53:44
这句话
ae = np.loadtxt(..., ndmin=2).reshape(-1, 4)
都适用于这两种情况。-1
告诉NumPy根据平面化输入数组的大小来猜测行数。
https://stackoverflow.com/questions/44550194
复制相似问题