Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Force array of arrays when using numpy genfromtext

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]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading