loadtxt() expects every row to have the same number of columns and every value to be parseable as a number — it raises an error immediately if it encounters a missing value, an inconsistent row length, or non-numeric text it can't convert. The delimiter parameter specifies how columns are separated, whitespace by default, or a comma for typical CSV files, and skiprows lets you skip a fixed number of header lines at the top of the file before the actual data begins.
1Understanding np.loadtxt()
loadtxt() expects every row to have the same number of columns and every value to be parseable as a number — it raises an error immediately if it encounters a missing value, an inconsistent row length, or non-numeric text it can't convert. The delimiter parameter specifies how columns are separated, whitespace by default, or a comma for typical CSV files, and skiprows lets you skip a fixed number of header lines at the top of the file before the actual data begins.
loadtxt() has no built-in tolerance for missing or malformed values — it simply raises an error the moment it hits one; use np.genfromtxt() instead when your data might have missing values or minor inconsistencies that need to be handled gracefully.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt("data.csv", arr, delimiter=",", fmt="%d")
loaded = np.loadtxt("data.csv", delimiter=",")
print(loaded)2Practical Example
Here is a real-world application of np.loadtxt() showing how it is used in production NumPy code.
import numpy as np
with open("scores.csv", "w") as f:
f.write("name,math,science\nAlice,90,85\nBob,78,92\n")
scores = np.loadtxt("scores.csv", delimiter=",", skiprows=1, usecols=(1, 2))
print(scores)3Best Practices
Follow these guidelines when working with np.loadtxt():
1. Use loadtxt() specifically for clean, well-formed numeric text data with no missing values, where its speed and simplicity are an advantage
2. Use skiprows to skip header lines instead of manually stripping them from the file first
3. Reach for np.genfromtxt() instead of loadtxt() as soon as missing values, inconsistent rows, or mixed data types are a realistic possibility
Tip: loadtxt() has no built-in tolerance for missing or malformed values — it simply raises an error the moment it hits one; use np.genfromtxt() instead when your data might have missing values or minor inconsistencies that need to be handled gracefully.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
np.savetxt("data.csv", arr, delimiter=",", fmt="%d")
loaded = np.loadtxt("data.csv", delimiter=",")
print(loaded)