Updated March 28, 2023
Introduction to NumPy load
NumPy load in Python is used to load data from .txt file. Module loadtxt() is used to load the data from text files having same number of values in each row of a text file. NumPy is imported using ‘np’ alias word. Alias being an alternate word to refer the same thing. So we shall start referring NumPy as np. np.loadtxt() offers flexibility over reading data from files as user can specify the type of data in result, also can distinguish among data entries through delimiters, users can also include or skip complete row. It is a fast reader for simple text files.
Syntax of NumPy load
Given below is the syntax of NumPy load:
numpy.loadtxt(fname, dtype=<class=float>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None)
Let us look at each of the parameters listed in the syntax:
- fname: The file, pathlib.path or str.
File, generator to read or filename, in cases where file extensions are .gz or .bz2, the file has to be first decompressed. Generators return only byte strings.
- dtype: Data type is an optional parameter.
This defines the data type of the resulting array with the default value ‘float’. In cases where the resulting array is a structured data type, array will be 1-dimensional, each row is interpreted as elements of an array. This case to occur, number of columns used should match number of fields of data type.
- comments: This being an optional parameter with str or sequence of str.
Used to indicate starting of a comment, default being ‘#’, For no comments, we can use ‘None’.
- delimiter: This being an optional parameter with str.
String here is used to separate values, with default being whitespace. Byte strings are decoded as ‘latin1’ in case of backwards compatibility.
- converters: This being an optional parameter with dictionary.
Converters define dictionary mapping column number to a function which will convert the column mapped to float.
- skiprows: This being an optional with integer.
Default value being 0, used to skip the first ‘skiprows’.
- usecols: This being an optional parameter with integer or sequence.
Defines columns to be read, with 0 as first. Usecols=(2,3,5) will extract 3rd, 4th and the 6th column. Default being None which results in all columns being read.
- unpack: This being an optional parameter with Boolean.
Returned array is transposed if parameter is set to ‘true’, and arguments get unpacked using x, y, and z. Default being set to ‘False’.
- ndmin: This being an optional parameter with integer.
Returned array has ndmin dimensions else mono dimensional axes will be squeezed.
- encoding: This being an optional parameter with str.
Encoding is used to decode the input file. default value being ‘bytes’, if set to None, systems default is used.
- max_rows: This being an optional value integer.
Default being to read lines in text file, max_rows of lines are read after skiprows.
Before executing examples of NumPy, we need to install Python and PIP, so that installation of NumPy would become easier.
Once NumPy is installed, we need to import NumPy using keyword: ‘import numpy’, so now NumPy has been imported and is ready to use.
Examples of NumPy load
Given below are the examples of NumPy load:
Example #1
Code:
import numpy as np
sample_array = np.array([20,30,50,60,80])
print('Array: ', sample_array);
Output:
Example #2
Code:
import numpy as np
from io import StringIO
multi = StringIO(u"7 2 20\n 39 40 30\n")
multi_array = np.loadtxt(multi)
print('Multi dimensional array: ', multi_array)
Output:
Example #3
Code:
import numpy as np
from io import StringIO
delimitArray = StringIO("23, 56, 34\n43, 65, 32")
a, b, c = np.loadtxt(delimitArray, delimiter =', ', usecols =(0, 1, 2), unpack = True)
print("a is: ", a)
print("b is: ", b)
print("c is: ", c)
Output:
Example #4
Code:
import numpy as np
from io import StringIO
d = StringIO("25 60 F\n23 90 M")
sample_details = np.loadtxt(d, dtype ={'names': ('age', 'weight', 'gender'), 'formats': ('i4', 'f4', 'S1')})
print('Age, Weight and Gender: ', sample_details)
Output:
Example #5
Code:
import numpy as np
from io import StringIO
sub_array = StringIO('24.03 67.32-\n22.19 31.06\n57.71- 63.70-')
def conv(fld):
return -float(fld[:-1]) if fld.endswith(b'-') else float(fld)
sub = np.loadtxt(sub_array, converters={0: conv, 1: conv})
print(sub)
Output:
How does NumPy work?
Let us consider example 2 above for some explanation.
- We have imported NumPy with an alias name np.
- Then have imported StringIO from io.
- We have declared a variable ‘multi’, with assigning return value of StringIO() function.
- Then, we have passed the ‘multi’ value to np.loadtxt() which will load the data from ‘multi’ and is displayed on console.
Conclusion
We have seen what NumPy Load is, it’s a method in Python. Python being a simple language to learn. Arguments in syntax are the main keywords with which we can modify and create programs with .loadtxt(). Illustrated few examples of np.loadtxt() for better understanding of the concept. Also have seen the process of how NumPy load works.
Recommended Articles
This is a guide to NumPy load. Here we discuss the introduction, examples of NumPy load along with how does the NumPy work? You may also have a look at the following articles to learn more –