csv_stats.py in Python
Summary statistics for one CSV column, stdlib only.
import csv
import statistics
import sys
def column_stats(path, column):
with open(path, newline="") as f:
values = [float(row[column]) for row in csv.DictReader(f)
if row.get(column)]
if not values:
raise SystemExit(f"no values in column {column!r}")
return {
"count": len(values),
"mean": statistics.mean(values),
"median": statistics.median(values),
"stdev": statistics.stdev(values) if len(values) > 1 else 0.0,
}
def main():
if len(sys.argv) != 3:
raise SystemExit(f"usage: {sys.argv[0]} FILE COLUMN")
path, column = sys.argv[1], sys.argv[2]
for name, value in column_stats(path, column).items():
print(f"{name:>8}: {value:.3f}")
if __name__ == "__main__":
main()
How it works
csv.DictReaderyields rows as dicts keyed by header.- Values parse to float; blanks are skipped.
- The
statisticsmodule supplies mean, median, and stdev.
Keywords and builtins used here
ascolumn_statsdefelsefloatforiflenmainopenprintraisereturnwith
The run, in numbers
- Lines
- 29
- Characters to type
- 673
- Tokens
- 215
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 117 seconds.
Step 5 of 5 in Encore, step 72 of 72 in Language basics.