Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a way to let numpy.loadtxt(fname, ..) create an array of shape (0, ncol), where ncol is an intenger specified by me, when fname is an empty file?

For example, if I run the following script,

#!/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)

with the files, 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

and fempty.dat

# This is an empty file

I see the following stdout from 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)

The length of the second dimension seems to be set automatically as 1 when there is no line to read-in but ndmin=2. Setting usecols did not seem to help.

Do I need to do something like the following?

if ae.shape[0]==0:
    ae.reshape((0,ncol))
like image 720
norio Avatar asked Mar 17 '26 13:03

norio


1 Answers

The statement

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

will work for both cases. The -1 tells NumPy to guess the number of rows based on the size of the flattened input array.

like image 166
Saullo G. P. Castro Avatar answered Mar 19 '26 01:03

Saullo G. P. Castro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!