3

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))
2
  • if ae.size == 0: ae = ae.reshape((0, ncol)) Commented Jun 14, 2017 at 16:49
  • Or just a conditional ae = zeros((0, ncol)). Commented Jun 14, 2017 at 17:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.