np.genfromtxt()
genfromtxt loads text data that has missing values or headers, filling the gaps for you.
In this page:
Syntax
data = np.genfromtxt("file.csv", delimiter=",", skip_header=1)
np.genfromtxt()
genfromtxt is a more forgiving reader than loadtxt. It can skip headers, handle missing entries by filling with nan or another value, and read column names. It is the tool to reach for with messy real-world data.
Note:
Use names=True to take column names from the first row.
Example: np.genfromtxt()
import numpy as np
import io
text = "1,2,3\n4,,6\n7,8,9"
a = np.genfromtxt(io.StringIO(text), delimiter=",")
print(a)
b = np.genfromtxt(io.StringIO(text), delimiter=",", filling_values=0)
print(b)
# Output:
# [[ 1. 2. 3.]
# [ 4. nan 6.]
# [ 7. 8. 9.]]
# [[1. 2. 3.]
# [4. 0. 6.]
# [7. 8. 9.]]
Related Topics
Common Mistakes
- Using loadtxt on files with blanks
- Forgetting skip_header
- Not choosing filling_values for missing data
Chapter Summary
- genfromtxt tolerates missing data
- skip_header skips lines
- names=True reads a header
- Missing values become nan by default
🔒
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: