How to use numpy genfromtxt in Python with examples

In this tutorial, we will be learning how to use numpy genfromtxt in Python with some basic and simple examples.

This tutorial is based on importing the CSV file in Python when we want to use NumPy. You might be familiar with Python and its modules, NumPy is one of its modules that deals with a large amount of data using arrays.

When all the data types are similar, we can use loadtxt() function which takes into account loading all the data in text format but the condition is all the data must be of similar data type.

Today, we will have a brief discussion on how to import a CSV file with different data types present using genfromtxt.

There are a few things to keep in mind while working on this task-

delimiter: It tells how to split a non-empty string into a sequence of strings.

dtype: It refers to data type, when working with genfromtxt, prefer None.

skip_header: It works to skip n lines from the top(Optional).

skip_footer: It works to skip n lines from the bottom(Optional).

There are some more parameters used but for now, we will deal with only above mentioned.

Example of genfromtxt in Python program

Considering you have a CSV file with different data types so it is obvious that loadtxt won’t work in this case. So we will use genfromtxt which is efficient in this case.

Implementation

You should have your file in the same path you are working on, in short, the python file and CSV file must be at the same location.

Open your compiler. Import NumPy and then use the parameters and check its shape mentioned above as-

import numpy as np

array=np.genfromtxt('cellformat.csv',dtype=None,delimiter=',')

array.shape

(10, 3)

We can see that the above output results in (10,3), are correct as per my data in the CSV file.

Here is the code enclosed-

import numpy as np
array=np.genfromtxt('cellformat.csv',dtype=None,delimiter=',')
array.shape

So, we completed the task to import a CSV file, then printed its shape to check if the syntax used was correct and the code was efficient.

You can try to skip the header and footer too, where the syntax would be skip_header=n or skip_footer=n.

n is the number of lines to be skipped, and n=0 means no line to be skipped.

I hope you enjoyed reading and working practically with this tutorial. Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *