Load text file into NumPy array (ndarray) using genfromtext() function

The numpy genfromtext() function is more sophisticated than the loadtxt() function in terms of handling the missing values and replacing them with a specified values.

Read Write Files Updated 8 Aug 2024 1 min read

Overview

  • The numpy function genfromtext() generates an ndarray from a text file.
  • It differs from loadtxt() that genfromtext() can handle missing values and replace them with specific values. Similar to loadtxt() the function genfromtext() also support converting values of columns on the fly.
  • The function genfromtext() is flexible in handling the inconsistencies present in the number of columns. It can be specified to raise an exception or to skip the rows where column number anomalies exist.

Example

python
# Example Python program that reads from a text

            # file and creates an ndarray. The genfromtxt()

            # also treats the missing values by filling them with a

            # zero

import numpy

dataFile = "quotes.txt"

            data = numpy.genfromtxt(dataFile,

                                    delimiter=",",

                                    missing_values = '',

                                    filling_values = 0,

                                    autostrip = False)

            numpy.set_printoptions(formatter={'float_kind':'{:f}'.format})

            print(data)

Input file

python
# Strike price, option(call - 0, put - 1), price, Price of Underlying

            110.0,0,8,102 # 110 call

            110.0,1,10,102 # 110 put

            120.0,0,4,102 # 120 call

            120.0,1,22,102 # 120 put

            130.0,0,1, # 130 call

            130.0,1,30,5290.50 # 130 put

Output

Output
[[110.000000 0.000000 8.000000 102.000000]

 [110.000000 1.000000 10.000000 102.000000]

 [120.000000 0.000000 4.000000 102.000000]

 [120.000000 1.000000 22.000000 102.000000]

 [130.000000 0.000000 1.000000 0.000000]

 [130.000000 1.000000 30.000000 5290.500000]]