← Back to NumPy Course | Chapter 11: File I/O | Lesson 4 of 5

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:

  1. Working with CSV
Syntax
python
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

python
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
  1. Trying to load text columns into a float array
  2. Forgetting to skip the header row
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.