0

Sample text input file:

35.6 45.1
21.2 34.1
30.3 29.3

When you use numpy.genfromtxt(input_file, delimiter=' '), it loads the text file as an array of arrays

[[35.6 45.1]
 [21.2 34.1]
 [30.3 29.3]]

If there is only one entry or row of data in the input file, then it loads the input file as a 1d array [35.6 45.1] instead of [[35.6 45.1]]

How do you force numpy to always result in a 2d array so that the resulting data structure stays consistent whether the input is 1 row or 10 rows?

1

1 Answer 1

1

Use the ndmin argument (new in 1.23.0):

numpy.genfromtxt(input_file, ndmin=2)

If you're on a version before 1.23.0, you'll have to do something else. If you don't have missing data, you can use numpy.loadtxt, which supports ndmin since 1.16.0:

numpy.loadtxt(input_file, ndmin=2)

Or if you know that your input will always have multiple columns, you can add the extra dimension with numpy.atleast_2d:

numpy.atleast_2d(numpy.genfromtxt(input_file))

(If you don't know how many rows or columns your input will have, it's impossible to distinguish the genfromtxt output for a single row or a single column, so atleast_2d won't help.)

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

1 Comment

Need to use numpy 1.17.3 and the second code block works. Thank you for writing solutions for multiple versions of numpy!

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.