Numpy is an acronym for ‘Numerical Python’. It is a library in python for supporting n-dimensional arrays. But have you ever wondered about loading data into NumPy from text files. Don’t worry we will discuss the same in this article. To import Text files into Numpy Arrays, we have two functions in Numpy: Show
Note: numpy.loadtxt( ) is equivalent function to numpy.genfromtxt( ) when no data is missing. Method 1 : numpy.loadtxt() Syntax :
The default data type(dtype) parameter for numpy.loadtxt( ) is float. Example 1: Importing Text file into Numpy arrays The following ‘example1.txt’ text file is considered in this example. Python3
Output : [[ 1 2] [ 3 4] [ 5 6] [ 7 8] [ 9 10]] Example 2: Importing text file into NumPy array by skipping first row Python3
Output : [['2' 'Bunty'] ['3' 'Tinku'] ['4' 'Rina']] Example 3: Importing only the first column(Names) of text file into numpy arrays The indexing in NumPy arrays starts from 0. Hence, the Roll column in the text file is the 0th column, Names column is the 1st column and the Marks are the 2nd column in the text file ‘example3.txt’. Python3
Output : Ankit Bunty Tinku Rina Rajesh Method 2 : numpy.genfromtxt() Syntax :
Except the fname(filename) in numpy.genfromtxt( ), all the other parameters are optional. Example 1: Python3
Output : [['a' 'b' 'c' 'd'] ['e' 'f' 'g' 'h']] Example 2: Importing text file into numpy arrays by skipping last row Python3
Output : [['This' 'is' 'GeeksForGeeks' 'Website'] ['How' 'are' 'You' 'Geeks?'] ['Geeks' 'for' 'Geeks' 'GFG']] |