numpy.loadtxt() in Python
Last Updated :
19 Mar, 2025
numpy.loadtxt() function is
used to load data from a text file and return it as a NumPy array. It is ideal for reading large data sets that are stored in simple text formats, such as CSV files or space-separated files.
Example: Basic Usage of numpy.loadtxt() for Reading a Simple Space-Separated File
This code demonstrates how to use numpy.loadtxt() to read a space-separated text file-like object. The data is loaded from the StringIO object (which simulates a file) into a NumPy array.
Python
import numpy as geek
# StringIO behaves like a file object
from io import StringIO
c = StringIO("0 1 2 \n3 4 5")
d = geek.loadtxt(c)
print(d)
Output :
[[ 0. 1. 2.] [ 3. 4. 5.]]
Explanation:
- The input data consists of numbers separated by spaces and newline characters.
- numpy.loadtxt() reads the data and stores it in a NumPy array, which is then printed.
Syntax
numpy.loadtxt(fname, dtype=<class ‘float’>, delimiter=None, converters=None,
skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=’bytes’,
comments=’#’, autostrip=False)
Parameters
- fname (required): The file name (or file-like object) to read. This can be a string (file path) or an open file object.
- dtype (optional): Data type of the resulting array. By default, the data is read as a float. You can specify another type, such as int.
- delimiter (optional): The string used to separate values in the file. Common delimiters include commas (,), spaces, or tabs. By default, whitespace is used.
- converters (optional): A dictionary of functions to convert data in specific columns. This allows custom conversions for specific columns in the input.
- skiprows (optional): Number of lines to skip at the beginning of the file. This is useful if your file has a header or metadata that should be ignored.
- usecols (optional): A tuple or list of integers indicating which columns to read from the file. If None, all columns are read.
- unpack (optional): If True, the columns of the data are transposed. This allows for unpacking data into separate arrays.
- ndmin (optional): Specifies the minimum number of dimensions for the resulting array. Default is 0, meaning it will return a 1D array.
- encoding (optional): Specifies the encoding of the file. The default is ‘bytes’, but you can use other encodings like ‘utf-8’.
- comments (optional): Character or string indicating the beginning of comments in the file (default is #).
- autostrip (optional): If True, strips leading and trailing whitespaces from each line.
Return Value
The numpy.loadtxt() function returns a NumPy array containing the data from the specified text file. The shape and data type of the array depend on the file content and any parameters specified, such as dtype (for data types), delimiter (for separating values), and usecols (for selecting specific columns).
Example Usage of numpy.loadtxt()
1. Using numpy.loadtxt() with Delimiters, usecols, and unpack for Reading CSV-Like Data
This example shows how numpy.loadtxt() can be used to read data from a CSV-like file with a custom delimiter. The usecols parameter is used to select specific columns, and the unpack parameter allows for unpacking the columns into separate arrays.
Python
import numpy as geek
# StringIO behaves like a file object
from io import StringIO
c = StringIO("1, 2, 3\n4, 5, 6")
x, y, z = geek.loadtxt(c, delimiter =', ', usecols =(0, 1, 2),
unpack = True)
print("x is: ", x)
print("y is: ", y)
print("z is: ", z)
Output :
x is: [ 1. 4.]
y is: [ 2. 5.]
z is: [ 3. 6.]
Explanation:
- The data is a CSV-like string, with numbers separated by commas.
- numpy.loadtxt() reads the data, selects columns using usecols, and unpacks the columns into separate variables (x, y, z).
2. Reading Structured Data with numpy.loadtxt() Using dtype for Named Fields
In this example, numpy.loadtxt() is used to read structured data with multiple fields (e.g., gender, age, weight). The dtype parameter is used to define the structure and data types of each field.
Python
import numpy as geek
# StringIO behaves like a file object
from io import StringIO
d = StringIO("M 21 72\nF 35 58")
e = geek.loadtxt(d, dtype ={'names': ('gender', 'age', 'weight'),
'formats': ('S1', 'i4', 'f4')})
print(e)
Output :
[(b'M', 21, 72.) (b'F', 35, 58.)]
Explanation:
- The input data contains columns for gender, age, and weight.
- dtype is used to specify the column names (‘gender’, ‘age’, ‘weight’) and their data types (‘S1’ for strings, ‘i4’ for 4-byte integers, and ‘f4’ for 4-byte floats).
- The data is then loaded into a structured NumPy array with named fields.
Similar Reads
numpy.load() in Python
numpy.load() function return the input array from a disk file with npy extension(.npy). Syntax : numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding='ASCII') Parameters: file : : file-like object, string, or pathlib.Path.The file to read. File-like objects must support the
2 min read
numpy.matrix() in Python
This class returns a matrix from a string of data or array-like object. Matrix obtained is a specialised 2D array. Syntax : numpy.matrix(data, dtype = None) : Parameters : data : data needs to be array-like or string dtype : Data type of returned array. Returns : data interpreted as a matrix # Pytho
1 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
json.load() in Python
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json . To use this feature, we import the json package in Pyth
4 min read
json.loads() in Python
JSON is a lightweight data format used for storing and exchanging data across systems. Python provides a built-in module called json to work with JSON data easily. The json.loads() method of JSON module is used to parse a valid JSON string and convert it into a Python dictionary. In this article, we
4 min read
Load NumPy data in Tensorflow
In this article, we will be looking at the approach to load Numpy data in Tensorflow in the Python programming language. Using tf.data.Dataset.from_tensor_slices() function Under this approach, we are loading a Numpy array with the use of tf.data.Dataset.from_tensor_slices() method, we can get the s
2 min read
numpy.fromstring() function â Python
numpy.fromstring() function create a new one-dimensional array initialized from text data in a string. Syntax : numpy.fromstring(string, dtype = float, count = -1, sep = ' ') Parameters : string : [str] A string that contained the data. dtype : [data-type, optional] Data-type of the array. Default d
1 min read
Multithreading in Python
This article covers the basics of multithreading in Python programming language. Just like multiprocessing , multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used. Let us first understand the concept of thread in computer architecture. What is a Process
8 min read
numpy.fromiter() function â Python
NumPy's fromiter() function is a handy tool for creating a NumPy array from an iterable object. This iterable can be any Python object that provides elements one at a time. The function is especially useful when you need to convert data from a custom data source, like a file or generator, into a Num
2 min read
Lazy import in Python
In this article, we will learn how to do Lazy import in Python. For this, let's first understand the lazy import. What is Lazy Import? It is a feature of the Pyforest module that allows the user to perform the task without adding libraries to the code snippet as the task of this function is to add t
5 min read