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
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