Learn Python

Import files with Python NumPy

If you know how to use python built-in open function to open text files, what if you now want to import a flat file and assign it to a variable ? if all the data are numerical you can use the package Numpy to import data as an Numpy array, now why would we want to do this ?  First, Numpy arrays are the Python standards for storing numerical data, they are efficient, fast and clean. Second Numpy arrays are often essential for other packages such as Scikit-learn a popular machine learning package for python, Numpy itself has a number of built-in functions that make it far easier and more efficient for import data as arrays enter the Numpy functions load text.

To use either of these we first need to import Numpy, we then call load text and pass at the file name as the first argument along with the delimiter as second argument, note that the default delimiter is any white space so we’ll usually to specify it explicitly.

There are a number of additional arguments you may wish to specify if for example your data consists of numeric and your header has string in it such as in the endless digits data, you will want to skip the first row by calling : load text with the arguments skip rows 1

If you want only the first and third columns of the data you’ll want to set use equal to the list containing int 0 and 2, you can also import differs are ntdata types into Numpy arrays for example setting the argument dtype equal string, will ensure that all entries are imported as string load text is great for basics cases but trends to break down when we have mixed data types, for example

Columns consisting floats and columns consisting of string, such we saw in the Titanic data set, now is your turn, to have fun with low text, you will also gain hands-on experience with other functions that can handle mixed data types.

In the next article we’ll see that although Numpy arrays can handle data of mixed types.

If you like this article, follow us in our facebook page : the over day and let’s your friends know by sharing it on social media.