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
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 Pytho
3 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. For example:Pythoni
4 min read
Pathlib module in Python Pathlib module in Python offers classes and methods to quickly perform the most common tasks involving file system paths, incorporating features from several other standard modules like os.path, glob, shutil, and os.Path classes in Pathlib module are divided into pure paths and concrete paths. Pure
6 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
Platform Module in Python Platform module in Python is a built-in library that provides a portable way to access detailed information about the underlying platform (hardware and operating system) on which your Python program is running. This can include data such as the OS name and version, machine type, processor info and P
3 min read
Python | os.isatty() method OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. os.isatty() method in Python is used to check whether the specified file descript
2 min read
Python orjson.loads() Method Python orjson.loads() method is used to deserialize a JSON string into a Python object using the orjson library of Python. In this article, we will learn about the Python orjson.loads() function. What is Python orjson.loads() Method?The orjson.loads() function is part of the orjson library and is us
2 min read
File Handling in Python File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
7 min read
Python Circular Imports The Circular Imports in Python programming occur when two or more modules mutually depend on each at the same time forming a loop between them. These modules' dependency on each other often results in the program getting stuck and generating circular import errors. What does the Python Circular Erro
4 min read