52 lines
1.4 KiB
Python
Executable File
52 lines
1.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""csv_summary.py — Read a CSV from stdin or a file argument and emit JSON summary statistics."""
|
|
|
|
import sys
|
|
import json
|
|
import csv
|
|
from collections import defaultdict
|
|
from statistics import mean, median
|
|
|
|
def summarize_csv(path=None):
|
|
fh = open(path, newline='') if path else sys.stdin
|
|
reader = csv.DictReader(fh)
|
|
rows = list(reader)
|
|
fh.close() if path else None
|
|
|
|
if not rows:
|
|
return {"rows": 0, "columns": [], "numeric": {}}
|
|
|
|
columns = reader.fieldnames or []
|
|
numeric = {}
|
|
for col in columns:
|
|
values = []
|
|
for row in rows:
|
|
try:
|
|
values.append(float(row[col]))
|
|
except (ValueError, TypeError):
|
|
pass
|
|
if values:
|
|
numeric[col] = {
|
|
"count": len(values),
|
|
"sum": round(sum(values), 4),
|
|
"mean": round(mean(values), 4),
|
|
"median": round(median(values), 4),
|
|
"min": round(min(values), 4),
|
|
"max": round(max(values), 4),
|
|
}
|
|
|
|
return {
|
|
"rows": len(rows),
|
|
"columns": columns,
|
|
"numeric": numeric,
|
|
}
|
|
|
|
def main():
|
|
path = sys.argv[1] if len(sys.argv) > 1 else None
|
|
result = summarize_csv(path)
|
|
json.dump(result, sys.stdout, indent=2)
|
|
sys.stdout.write("\n")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|