A447 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 47 · Text and CSV data

Getting measurements out of files

Oscilloscopes, data loggers, spreadsheets and simulators all export the same thing: a text file of comma-separated values, with a header line naming the columns, maybe some comment lines, and the occasional blank or broken entry. Before any analysis, you have to read that file into arrays without losing or misreading a value. Python's csv module and NumPy's loaders do it in a line or two, once you know which to use.

Predict

A CSV file's first line is t,v,i and the rest are numbers. What does np.loadtxt(f, delimiter=",") do with it?

Name it

CSV text

A CSV ("comma-separated values") file is plain text:

# logged 2026-11-18, channel A
t,v,i
0.000,0.00,1.000
0.001,0.95,0.905
0.002,1.81,0.819

In these browser labs the "file" is a string, wrapped by io.StringIO so it behaves like an open file. On your own machine you'd use open("data.csv") in its place.

Three ways to read it

csv.DictReader: each row becomes a dictionary keyed by the header names. Flexible, and good for mixed text and numbers.

import csv, io
rows = list(csv.DictReader(io.StringIO(text)))
v = [float(r["v"]) for r in rows]

np.loadtxt: fast, for clean numeric data.

data = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=2)
t, v, i = data.T          # columns, by unpacking the transpose

skiprows counts every line from the top, comment lines included, so here it skips the comment and the header. (Comment lines further down are dropped automatically: comments="#" is the default.)

np.genfromtxt: like loadtxt, but turns missing or unreadable entries into nan (not a number) instead of failing.

data = np.genfromtxt(io.StringIO(text), delimiter=",", skip_header=1)
np.nanmean(data[:, 1])    # the mean, ignoring the nan entries
np.isnan(data).sum()      # how many entries were missing

Writing CSV

lines = ["f,gain_db"] + [f"{fi:g},{gi:.3f}" for fi, gi in zip(f, g)]
text = "\n".join(lines)

or csv.writer for anything with quoting. Always write a header: a column of numbers with no name is useless six months later.

Habits that prevent errors

  • Print the first few rows and the shape before you analyze anything.
  • Check units: a header like i_mA tells you to scale.
  • Count missing values instead of silently dropping them.

Worked example

Read the three-column log above and find the power at each sample.

Show the solution
  1. Load the columns. skiprows=2 skips the comment line and the header, and .T splits the columns into t, v and i.
  2. Multiply. The power at each sample is v×i.
import io, numpy as np
text = """# logged 2026-11-18, channel A
t,v,i
0.000,0.00,1.000
0.001,0.95,0.905
0.002,1.81,0.819"""
t, v, i = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=2).T
print(v * i)          # [0.      0.85975 1.48239]
  1. If the skip is wrong. Get it wrong by one and loadtxt stops with a ValueError on the header, which is a safe way to fail.

Answer the power at the three samples is 0, 0.85975 and 1.48239.

Worked example

A log has a missing value. Find the mean of each column anyway.

Show the solution
  1. Read with genfromtxt. The blank entry becomes nan.
  2. Average around the gap. np.nanmean averages the three good values of v.
text = "t,v\n0,1.0\n1,\n2,1.2\n3,1.1"
data = np.genfromtxt(io.StringIO(text), delimiter=",", skip_header=1)
print(np.isnan(data).sum(), np.nanmean(data, axis=0))     # 1 [1.5 1.1]

Answer one value is missing, and the column means are 1.5 for t and 1.1 for v.

Check

Read the CSV text in the starter with csv.DictReader. Set names to the list of header names, n to the number of data rows, and vmax to the largest value in the v column.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Load the numeric CSV in the starter with np.loadtxt (it starts with a comment line and a header). Set t, v to its first two columns and avg to the mean of v.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

The log in the starter has missing entries. Read it with np.genfromtxt and set missing to how many values are missing and means to the mean of each column, ignoring them.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Compute an RC low-pass's gain in dB at f = [10, 100, 1000, 10000] for fc = 500 Hz, and set text to CSV with the header f,gain_db and the gains to three decimal places, one row per frequency, joined with "\n".

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Each line of the starter's log looks like 12:00:05,3.301: a time of day as hh:mm:ss, then a reading. Set secs to a list of each line's time in seconds since the first line, vals to the readings as floats, and rate to the average number of readings per second over the log (lines minus one, divided by the elapsed time).

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

What is "3.3;4.7;5".split(";")?

Explain why

Why is it better to have a loader turn a missing value into nan than to skip the row or treat it as zero?

Practice

Keep practicing

7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.