loadtxt and genfromtxt

Upload sample files, delimiters, comments, usecols, and missing tokens.

Download the sample files from the banner, then click Add files in the workbench. Comment lines starting with # are skipped. There are no string city columns — row order is Nairobi, Mombasa, Kisumu, Nakuru, Eldoret.

Goal

List /uploads, load units.csv and temps.txt, and read missing tokens with genfromtxt.

See what is attached

import os

print("uploads:", os.listdir("/uploads"))

If that list is empty, attach the files and run again.

CSV with a comma delimiter

import os

print("uploads:", os.listdir("/uploads"))
units = np.loadtxt("units.csv", delimiter=",")
prices = np.loadtxt("prices.csv")
print(units)
print("units shape:", units.shape)
print("prices:", prices, prices.shape)

units.csv is 5×3. prices.csv is a single column, so the shape is (3,).

Whitespace .txt

temps = np.loadtxt("temps.txt")
print(temps)
print("shape:", temps.shape)
print("column means (Nairobi, Mombasa, Kisumu):", temps.mean(axis=0))

Default delimiter is any whitespace. temps.txt is 7×3.

Useful loadtxt options

units = np.loadtxt("units.csv", delimiter=",", usecols=(0, 1))
print(units.shape)
print(units)

usecols keeps products A and B.

Missing tokens with genfromtxt

gaps = np.genfromtxt("gaps.csv", delimiter=",", missing_values="nan", filling_values=np.nan)
print(gaps)
print("nan count:", np.isnan(gaps).sum())
print("city nanmean:")
print(np.nanmean(gaps, axis=1))

loadtxt often accepts the token nan too. genfromtxt is the safer default for dirty files.

Pitfall

FileNotFoundError means the workbench cannot see the file in /uploads. Download from the banner, then Add files — the tutorial page cannot put files into the editor for you.