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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Matrix
  • 67
  • 1
  • 6
  • Does this answer your question? [Convert a 1D array to a 2D array in numpy](https://stackoverflow.com/questions/12575421/convert-a-1d-array-to-a-2d-array-in-numpy) – mkrieger1 Dec 01 '22 at 22:38

1 Answers1

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

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Need to use numpy 1.17.3 and the second code block works. Thank you for writing solutions for multiple versions of numpy! – Matrix Dec 01 '22 at 23:04