BetterDocs
Home
Docs

Creation | np.loadtxt()

Method:

np.loadtxt(fname, dtype=np.float64, comments='#', delimiter=' ', converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=None, max_rows=None, *, quotechar=None, like=None)

Loads data from a text file.

Returns:

np.ndarray

Parameters:

fname: filepath-

File name or file-like object.

import numpy as np

arr = np.array([1, 2, 3])
arr.tofile(file='data.txt', sep=",")  # Write as text
arr_from_file = np.loadtxt(fname='data.txt', delimiter=',')
print(arr_from_file)  # Output: [1. 2. 3.]

dtype: np.float64, Optional-

It will convert the elements to the specified data-type.

import numpy as np

arr = np.array([1, 2, 3])
arr.tofile(file='data.txt', sep=",")  # Write as text
arr_from_file = np.loadtxt(fname='data.txt', delimiter=',', dtype=np.float32)
print(arr_from_file)  # Output: [1. 2. 3.]

Values: +

comments: str, Optional-

Characters to skip as comments.

import numpy as np

with open('data.txt', 'w') as f:
  f.write("1,2,3,4^,5")
arr_from_file = np.loadtxt(fname='data.txt',comments='^', delimiter=',')
print(arr_from_file)  # Output: [1. 2. 3. 4.]

Everything from the same line after a comment is read is discarded.

delimiter: str, Optional-

Separator between values.

import numpy as np

with open('data.txt', 'w') as f:
  f.write("1*2*3*4^*5")
arr_from_file = np.loadtxt(fname='data.txt',comments='^', delimiter='*')
print(arr_from_file)  # Output: [1. 2. 3. 4.]

converters: None, Optional-

Functions to process columns.

import numpy as np

with open('data_converters.txt', 'w') as f:
    f.write("1.0, 2.0, A\n4.0, 5.0, B")

data = np.loadtxt('data_converters.txt', delimiter=',', converters={2: lambda s: ord(s.strip()) - ord('A')})
print(data)
# Output:
# [[1. 2. 0.]
#  [4. 5. 1.]]

skiprows: int, Optional-

The number of lines to skip at the beginning of the file.

import numpy as np

with open('data_skiprows.txt', 'w') as f:
    f.write("Header line\nAnother header\n1.0 2.0 3.0\n4.0 5.0 6.0")

data = np.loadtxt('data_skiprows.txt', skiprows=2)
print(data)
# Output:
# [[1. 2. 3.]
#  [4. 5. 6.]]

usecols: (None or tuple), Optional-

The columns to read, specified as indices.

import numpy as np

with open('data_usecols.txt', 'w') as f:
    f.write("1.0 2.0 3.0\n4.0 5.0 6.0")

data = np.loadtxt('data_usecols.txt', usecols=(0, 2))
print(data)
# Output:
# [[1. 3.]
#  [4. 6.]]

unpack: (True or False), Optional-

If True, the data is unpacked into separate arrays (one per column).

import numpy as np

with open('data_usecols.txt', 'w') as f:
    f.write("1.0 2.0 3.0\n4.0 5.0 6.0")

data1, data2, data3 = np.loadtxt('data_usecols.txt', unpack=True)
print(data1)  # Output: [1. 4.]
print(data2)  # Output: [2. 5.]
print(data3)  # Output: [3. 6.]

ndmin: int, Optional-

The minimum number of dimensions of the output array.

import numpy as np

# Write a simple data file with a single line
with open('data_single_line.txt', 'w') as f:
    f.write("1.0 2.0 3.0")

data_ndmin2 = np.loadtxt('data_single_line.txt', ndmin=2)
print("\nndmin=2 array shape:", data_ndmin2.shape)  # Output: (1, 3)
print("ndmin=2 array:", data_ndmin2)  # Output: [[1. 2. 3.]]

encoding: None, Optional-

The encoding to use when reading the file.

import numpy as np

with open('data_utf8.txt', 'w', encoding='utf-8') as f:
    f.write("1.0 2.0 3.0\n4.0 5.0 6.0")

data = np.loadtxt('data_utf8.txt', encoding='utf-8')
print(data)
# Output:
# [[1. 2. 3.]
#  [4. 5. 6.]]

max_rows: None, Optional-

The maximum number of rows to read.

import numpy as np

with open('data_utf8.txt', 'w', encoding='utf-8') as f:
    f.write("1.0 2.0 3.0\n4.0 5.0 6.0")

data = np.loadtxt('data_utf8.txt', encoding='utf-8', max_rows=1)
print(data)
# Output:
# [1. 2. 3.]

quotechar: None, Optional-

The character used to enclose data that contains delimiters.

import numpy as np
from io import StringIO

s = StringIO('"BetterDocs, is just ""BETTER""!"')
data = np.loadtxt(s, dtype="U", delimiter=",", quotechar='"')
print(data) # Output: BetterDocs, is just "BETTER"!

like: None, Optional-

The like parameter in np.loadtxt() was introduced to make array creation more flexible, particularly for compatibility with libraries that extend NumPy, like Dask, CuPy, or other libraries that create arrays compatible with np.ndarray but optimized for different backends (e.g., parallel processing or GPU-based arrays).


Logo

BetterDocs

Support

EmailDiscordForms

Documentations

Python

Company

AboutDocs

Policies

Terms of ServicePrivacy Policy