numpy.loadtxt() in Python (original) (raw)

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:

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

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:

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