How to use Numpy genfromtxt function?

Let’s see how to use Numpy genfromtxt function.

Numpy genfromtxt function python

Using genfromtxt method

The NumPy genfromtxt function lets you load file content into your Python code. I’m using genfromtxt like this:

import numpy as np
import os

os.chdir("C:/Users/Pythoneo/Documents/MyProjects")

a = np.genfromtxt("data.csv", dtype='float', delimiter=',')
print(a)

chdir allows setting the working directory. If not set, the genfromtxt function will use the current directory.

See also  How to resolve MemoryError: Unable to allocate array in Numpy?

Genfromtxt Numpy function is having various parameters.

  • The first one is file name.
  • The dtype parameter allows setting the data type. Remember, it should be a type appropriate for the data, often numerical types.
  • Delimiter in my example is a come because the file it is csv file.
  • How to set the skiprows parameter

    The skiprows parameter allows you to skip a specified number of rows at the beginning of the file. This can be useful if the file contains header rows or other rows that you do not want to load.

    See also  How to trim an array with Numpy clip?