Home > Software engineering >  Force array of arrays when using numpy genfromtext
Force array of arrays when using numpy genfromtext

Time:12-02

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?

CodePudding user response:

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

  • Related