Text Processing and DataFrames
Most data work starts with cleaning text and reading tables. This chapter covers both. First it cleans free text and reads CSV and JSON, from source-code/text_processing/. Then it builds a small dataframe and runs a real analysis over a housing dataset, from source-code/dataframe_example/.
Cleaning Free Text
The file text_processing/clean_text.ml prepares raw text for later processing. It does three things: it pushes spaces around punctuation so words and marks separate cleanly, it drops noise characters, and it removes common stop words.
The noise characters are a plain list, and substitute_noise_characters turns each one into a space:
1 let noise_characters =
2 [ '['; ']'; '{'; '}'; '\n'; '\t'; '&'; '^'; '@'; '%'; '$'; '#' ]
3
4 let substitute_noise_characters s =
5 String.map (fun c -> if List.mem c noise_characters then ' ' else c) s
String.map applies a function to every character and returns a new string. List.mem tests membership. The standard library has no String.replace, so the file supplies one built on a Buffer, which grows a string efficiently without rebuilding it each time:
1 let replace_str old_s new_s s =
2 let ol = String.length old_s in
3 if ol = 0 then s
4 else begin
5 let buf = Buffer.create (String.length s) in
6 let n = String.length s in
7 let i = ref 0 in
8 while !i < n do
9 if !i + ol <= n && String.sub s !i ol = old_s then begin
10 Buffer.add_string buf new_s;
11 i := !i + ol
12 end
13 else begin
14 Buffer.add_char buf s.[!i];
15 incr i
16 end
17 done;
18 Buffer.contents buf
19 end
This is imperative OCaml: a ref cell for the index, a while loop, and a Buffer that collects the result. When the text at the cursor matches old_s, it appends the replacement and jumps ahead; otherwise it copies one character. cleanText chains everything with the pipe operator:
1 let clean_text s =
2 s
3 |> replace_str ";" " ; "
4 |> replace_str "," " , "
5 |> replace_str "." " . "
6 |> substitute_noise_characters
7 |> String.split_on_char ' '
8 |> List.filter (fun x -> String.length x > 0)
9 |> String.concat " "
Read top to bottom: space out the semicolons, commas, and periods, turn noise into spaces, split on spaces, drop the empty pieces, and join back with single spaces. The result has clean, single-spaced tokens. Removing stop words is one more filter:
1 let stop_words = [ "a"; "the"; "that"; "of"; "an"; "and" ]
2
3 let remove_stop_words s =
4 String.split_on_char ' ' s
5 |> List.filter (fun x -> x <> "")
6 |> List.filter (fun x -> not (List.mem (String.lowercase_ascii x) stop_words))
7 |> String.concat " "
It splits into words and keeps only the ones that are not stop words, comparing in lower case so The and the both go.
Reading CSV
The csv library reads a comma-separated file into a list of rows, where each row is a list of string cells. The file text_processing/test_csv.ml loads a file and prints it, guarding against a parse error:
1 let read_csv_file fname =
2 try Csv.load fname
3 with e ->
4 Printf.printf "CSV parse error: %s\n" (Printexc.to_string e);
5 []
Csv.load returns string list list. Once you have that, ordinary list functions do the rest. The demo pulls the first column of every row with List.map List.hd, and splits the header from the body by matching the list:
1 match c with
2 | [] -> print_endline "Warning: CSV file is empty, no header or rows."
3 | header :: rows ->
4 print_endline (show_row header);
5 print_endline (show_csv rows)
Round-Tripping JSON
For JSON the book uses Yojson everywhere. A JSON value is a polymorphic variant: `Assoc for an object, `String for text, and so on. The file text_processing/test_json.ml encodes a record to JSON and reads it back:
1 type person = { name : string; email : string }
2
3 let person_to_json p =
4 `Assoc [ ("name", `String p.name); ("email", `String p.email) ]
5
6 let person_of_json j =
7 let open Yojson.Safe.Util in
8 { name = j |> member "name" |> to_string; email = j |> member "email" |> to_string }
To build JSON, you construct the variant directly: an `Assoc is a list of key-value pairs. To read it, the Yojson.Safe.Util module gives you accessors: member "name" pulls a field out of an object, and to_string reads it as a string. The j |> member "name" |> to_string pipeline reads left to right. Decoding is wrapped in a try so malformed input gives a clear message instead of an exception. This small encoder-decoder pattern is the same one the LLM and search chapters use for real API payloads.
A Small DataFrame
A dataframe is a table you can filter, sort, and aggregate by column name. The file dataframe_example/src/dataframe.ml builds one over the csv library. It stores every cell as a string and parses numbers on demand, which keeps the type simple:
1 type t = { columns : string array; rows : string array array }
2
3 let num s = Option.value ~default:0. (float_of_string_opt (String.trim s))
4
5 let index t name =
6 let rec go i =
7 if i >= Array.length t.columns then invalid_arg ("no such column: " ^ name)
8 else if t.columns.(i) = name then i
9 else go (i + 1)
10 in
11 go 0
A dataframe is a header array plus a two-dimensional array of string cells. num reads a cell as a float, defaulting to zero on junk. index finds a column’s position by name, which every other operation uses to reach a cell.
Loading and saving wrap Csv.load and Csv.save. The interesting operations are the transforms. derive adds a computed column. It hands your function an accessor g that reads any column of the current row as a float:
1 let derive t name f =
2 let cols = Array.append t.columns [| name |] in
3 let rows =
4 Array.map
5 (fun row ->
6 let g col = num row.(index t col) in
7 Array.append row [| fmt (f g) |])
8 t.rows
9 in
10 { columns = cols; rows }
So derive d "rooms_per_household" (fun g -> g "total_rooms" /. g "households") appends a new column computed from two existing ones. Filtering keeps the rows that pass a test, with one version for numeric columns and one for string columns:
1 let filter_float t name pred =
2 let i = index t name in
3 { t with rows = Array.of_list (List.filter (fun r -> pred (num r.(i)))
4 (Array.to_list t.rows)) }
select narrows to a set of columns, and sort_by_float sorts on a numeric column, ascending or descending, with Array.stable_sort so equal rows keep their order. The aggregation step groups rows by a key column and computes one or more aggregates per group:
1 type agg = Count | Mean of string
2
3 let group_by t ~key ~aggs =
4 let ki = index t key in
5 ...
6 let compute rows = function
7 | Count -> float_of_int (List.length rows)
8 | Mean src ->
9 let i = index t src in
10 let xs = List.map (fun r -> num r.(i)) rows in
11 (match xs with
12 | [] -> 0.
13 | _ -> List.fold_left ( +. ) 0. xs /. float_of_int (List.length xs))
14 in
15 ...
An aggregate is a small variant: Count, or Mean of a named column. The function collects the unique keys in first-seen order (using a Hashtbl to remember which it has seen), then for each key computes every requested aggregate. There is also summarize, which reports count, mean, min, and max for every numeric column, and print, which lays the table out with aligned columns.
The Housing Analysis
The driver dataframe_example/bin/main.ml runs a full analysis over a California housing sample. It reads the CSV, prints summary statistics, and derives three columns:
1 let enriched =
2 df
3 |> fun d ->
4 D.derive d "rooms_per_household" (fun g -> g "total_rooms" /. g "households")
5 |> fun d ->
6 D.derive d "population_per_household" (fun g ->
7 g "population" /. g "households")
8 |> fun d ->
9 D.derive d "bedrooms_per_room" (fun g ->
10 g "total_bedrooms" /. g "total_rooms")
11 in
It then filters for expensive coastal properties, sorts to find the most expensive, and groups by ocean proximity to compare average value and income across regions:
1 let by_proximity =
2 D.group_by enriched ~key:"ocean_proximity"
3 ~aggs:
4 [ ("num_districts", D.Count);
5 ("avg_house_value", D.Mean "median_house_value");
6 ("avg_income", D.Mean "median_income");
7 ("avg_rooms_per_hh", D.Mean "rooms_per_household") ]
8 |> fun d -> D.sort_by_float ~desc:true d "avg_house_value"
Finally it writes the enriched table back to a new CSV. The labelled arguments ~key and ~aggs make the call read almost like a sentence: group by ocean proximity, aggregating these four measures.
Running It
Run from the project root so the data file resolves:
1 cd source-code/dataframe_example
2 dune build
3 dune exec ./bin/main.exe
4 dune runtest
The program prints the first rows, the summary statistics, the derived columns, the expensive coastal listings, the top five by price, and the per-region averages, then writes ./data/housing_enriched.csv. In under 200 lines you have a working dataframe with derive, filter, select, sort, group, and aggregate, built from arrays, Hashtbl, and the csv library.