Open In App

numpy.loadtxt() in Python

Last Updated : 19 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Practice Tags :

Similar Reads