Import Text Files Into Numpy Arrays – Python
Last Updated :
03 Apr, 2025
We have to import data from text files into Numpy arrays in Python. By using the numpy.loadtxt() and numpy.genfromtxt() functions, we can efficiently read data from text files and store it as arrays for further processing.
- numpy.loadtxt( ) – Used to load text file data
- numpy.genfromtxt( ) – Used to load data from a text file, with missing values handled as defined.
Note: numpy.loadtxt( ) is equivalent function to numpy.genfromtxt( ) when no data is missing.
Using numpy.loadtxt()
numpy.loadtxt() function is one of the most commonly used methods to import data from a text file into a NumPy array. It can read a variety of text files that have structured data like numbers or strings, and it can handle delimiter-separated values such as CSV, TSV, or space-separated files.
Example 1: Importing Text file into Numpy arrays
The following ‘example1.txt’ text file is considered in this example.
Python
import numpy as np
# Text file data converted to integer data type
d = np.loadtxt("example1.txt", dtype=int)
print(d)
Output :
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]]
Explanation: This code uses the numpy.loadtxt() function to read data from the text file example1.txt and convert the data into a NumPy array with integer data type (dtype=int). The resulting array is then printed.
Example 2: Importing text file into NumPy array by skipping first row
Python
import numpy as np
# skipping first row
# converting file data to string
d = np.loadtxt("example2.txt", skiprows=1, dtype='str')
print(d)
Output :
[['2' 'Bunty']
['3' 'Tinku']
['4' 'Rina']]
Explanation: This code uses numpy.loadtxt() to read data from the text file example2.txt, skipping the first row and converting the remaining data into a NumPy array of strings (dtype=’str’). The resulting data is then printed.
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’.
Python
import numpy as np
# only column1 data is imported into numpy
# array from text file
d = np.loadtxt("example3.txt", usecols=1, skiprows=1, dtype='str')
for each in d:
print(each)
Output :
Ankit
Bunty
Tinku
Rina
Rajesh
Explanation: This code uses numpy.loadtxt() to read data from the text file example3.txt, skipping the first row and importing only the data from column 1 (usecols=1). The data is converted into strings (dtype=’str’). It then prints each value in the resulting array.
Using numpy.genfromtxt()
numpy.genfromtxt() is a more flexible function that can handle missing data, non-numeric data, and more complex file formats. It’s generally used when dealing with more complex text files.
Example 1: Importing Data with np.genfromtxt() in NumPy
Python
import numpy as np
d = np.genfromtxt("example4.txt", dtype=str, encoding=None, delimiter=",")
print(d)
Output :
[['a' 'b' 'c' 'd']
['e' 'f' 'g' 'h']]
Explanation: This code uses the numpy.genfromtxt() function to read data from the text file example4.txt. The data is read as strings (dtype=str), with no specific encoding (encoding=None), and is assumed to be comma-separated (delimiter=”,”). The resulting array is then printed.
Example 2: Importing text file into numpy arrays by skipping last row
Python
import numpy as np
# skipping last line in the file
d = np.genfromtxt("example5.txt", dtype=str, encoding=None, skip_footer=1)
print(d)
Output :
[['This' 'is' 'GeeksForGeeks' 'Website']
['How' 'are' 'You' 'Geeks?']
['Geeks' 'for' 'Geeks' 'GFG']]
Explanation: This code uses the numpy.genfromtxt() function to read data from the text file example5.txt, skipping the last line of the file (skip_footer=1). The data is read as strings (dtype=str) and no specific encoding is used (encoding=None). The resulting array is then printed.
Similar Reads
Convert Python List to numpy Arrays
NumPy arrays are more efficient than Python lists, especially for numerical operations on large datasets. NumPy provides two methods for converting a list into an array using numpy.array() and numpy.asarray(). In this article, we'll explore these two methods with examples for converting a list into
4 min read
Python Lists VS Numpy Arrays
Here, we will understand the difference between Python List and Python Numpy array. What is a Numpy array?NumPy is the fundamental package for scientific computing in Python. Numpy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operati
7 min read
numpy.array_str() in Python
numpy.array_str()function is used to represent the data of an array as a string. The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type. Syntax : numpy.array_st
2 min read
numpy.asarray_chkfinite() in Python
numpy.asarray_chkfinite() function is used when we want to convert the input to an array, checking for NaNs (Not A Number) or Infs(Infinities). Input includes scalar, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Syntax : numpy.asarray_chkfinite(arr, dtype=None, ord
2 min read
numpy.array_repr() in Python
numpy.array_repr()function is used to convert an array to a string. Syntax : numpy.array_repr(arr, max_line_width=None, precision=None, suppress_small=None) Parameters : arr : [array_like] Input array. max_line_width : [int, optional] The maximum number of columns the string should span. Newline cha
2 min read
Describe a NumPy Array in Python
NumPy is a Python library used for numerical computing. It offers robust multidimensional arrays as a Python object along with a variety of mathematical functions. In this article, we will go through all the essential NumPy functions used in the descriptive analysis of an array. Let's start by initi
3 min read
Python - Boolean Array in NumPy
In this article, I'll be explaining how to generate boolean arrays in NumPy and utilize them in your code. In NumPy, boolean arrays are straightforward NumPy arrays with array components that are either "True" or "False." Note: 0 and None are considered False and everything else is considered True.
3 min read
numpy.argsort() in Python
numpy.argsort() is a function in NumPy that returns the indices that would sort an array. In other words, it gives you the indices that you would use to reorder the elements in an array to be in sorted order. Example: [GFGTABS] Python import numpy as geek a = geek.array([2, 0, 1, 5, 4, 1, 9]) print(
3 min read
NumPy Array in Python
NumPy (Numerical Python) is a powerful library for numerical computations in Python. It is commonly referred to multidimensional container that holds the same data type. It is the core data structure of the NumPy library and is optimized for numerical and scientific computation in Python. Table of C
2 min read
Different Ways to Create Numpy Arrays in Python
Creating NumPy arrays is a fundamental aspect of working with numerical data in Python. NumPy provides various methods to create arrays efficiently, catering to different needs and scenarios. In this article, we will see how we can create NumPy arrays using different ways and methods. Ways to Create
3 min read