Skip to main content
 首页 » 编程设计

Python numpy loadtxt : reading an empty file into an array with a particular number of columns

2025年02月15日9TianFang

有没有办法让numpy.loadtxt(fname, ..)创建一个形状为(0, ncol)的数组,其中ncol是我指定的整数,当fname是一个空文件?

例如,如果我运行以下脚本,

#!/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 中看到以下标准输出

$ ./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)) 

请您参考如下方法:

声明

ae = np.loadtxt(..., ndmin=2).reshape(-1, 4) 

将适用于这两种情况。 -1 告诉 NumPy 根据展平输入数组的大小猜测行数。