Working with CSV
CSV files are just text with commas, so loadtxt and genfromtxt can read them and savetxt can write them.
In this page:
Syntax
data = np.loadtxt("file.csv", delimiter=",", skiprows=1)
np.savetxt("out.csv", data, delimiter=",")
Working with CSV
For purely numeric CSV files, NumPy's text functions are enough. Use skiprows or skip_header for titles and usecols to pick columns. For mixed text and numbers, Pandas is usually more convenient.
Note:
dtype=None with genfromtxt and names=True builds a structured array from mixed columns.
Example: Working with CSV
import numpy as np
import io
csv = "height,weight\n170,65\n180,80\n160,50"
data = np.loadtxt(io.StringIO(csv), delimiter=",", skiprows=1)
print(data)
print("mean weight:", data[:, 1].mean())
# Output:
# [[170. 65.]
# [180. 80.]
# [160. 50.]]
# mean weight: 65.0
Related Topics
Common Mistakes
- Trying to load text columns into a float array
- Forgetting to skip the header row
- Using NumPy where Pandas would be easier
Chapter Summary
- Skip the header row
- usecols selects columns
- Numeric-only CSVs suit NumPy
- Use Pandas for mixed data
🔒
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: