Reading and writing data

Data comes from files, and goes back into them. This chapter reads CSV, JSON and NDJSON, and writes CSV and Parquet.

Reading CSV Files

import std/strutils
echo readFile("data/definitive-guide/penguins.csv").splitLines[0 .. 4].join("\n")
"rowid","species","island","bill_length_mm","bill_depth_mm","flipper_length_mm","body_mass_g","sex","year"
"1","Adelie","Torgersen",39.1,18.7,181,3750,"male",2007
"2","Adelie","Torgersen",39.5,17.4,186,3800,"female",2007
"3","Adelie","Torgersen",40.3,18,195,3250,"female",2007
"4","Adelie","Torgersen",NA,NA,NA,NA,NA,2007
import nanuq

var penguins = readCsv("data/definitive-guide/penguins.csv")
nbShow penguins
shape: (344, 9)
rowidspeciesislandbill_length_mmbill_depth_mmflipper_length_mmbody_mass_gsexyear
i64strstrstrstrstrstrstri64
1"Adelie""Torgersen""39.1""18.7""181""3750""male"2007
2"Adelie""Torgersen""39.5""17.4""186""3800""female"2007
3"Adelie""Torgersen""40.3""18""195""3250""female"2007
4"Adelie""Torgersen""NA""NA""NA""NA""NA"2007
5"Adelie""Torgersen""36.7""19.3""193""3450""female"2007
………………………
340"Chinstrap""Dream""55.8""19.8""207""4000""male"2009
341"Chinstrap""Dream""43.5""18.1""202""3400""female"2009
342"Chinstrap""Dream""49.6""18.2""193""3775""male"2009
343"Chinstrap""Dream""50.8""19""210""4100""male"2009
344"Chinstrap""Dream""50.2""18.7""198""3775""female"2009

Parsing Missing Values Correctly

The file writes missing values as NA, so the numeric columns with one came out as strings. null_values says how missing values look:

penguins = readCsv("data/definitive-guide/penguins.csv", nullValues = ["NA"])
nbShow penguins
shape: (344, 9)
rowidspeciesislandbill_length_mmbill_depth_mmflipper_length_mmbody_mass_gsexyear
i64strstrf64f64i64i64stri64
1"Adelie""Torgersen"39.118.71813750"male"2007
2"Adelie""Torgersen"39.517.41863800"female"2007
3"Adelie""Torgersen"40.318.01953250"female"2007
4"Adelie""Torgersen"nullnullnullnullnull2007
5"Adelie""Torgersen"36.719.31933450"female"2007
………………………
340"Chinstrap""Dream"55.819.82074000"male"2009
341"Chinstrap""Dream"43.518.12023400"female"2009
342"Chinstrap""Dream"49.618.21933775"male"2009
343"Chinstrap""Dream"50.819.02104100"male"2009
344"Chinstrap""Dream"50.218.71983775"female"2009
nbShow penguins.select(all().nullCount).transpose(
  includeHeader = true, columnNames = ["null_count"])
shape: (9, 2)
columnnull_count
stru32
"rowid"0
"species"0
"island"0
"bill_length_mm"2
"bill_depth_mm"2
"flipper_length_mm"2
"body_mass_g"2
"sex"11
"year"0

Reading JSON and NDJSON

JSON

The Pokédex is one JSON object, with a list of Pokémon:

echo readFile("data/definitive-guide/pokedex.json").splitLines[0 .. 15].join("\n")
{
  "pokemon": [{
    "id": 1,
    "num": "001",
    "name": "Bulbasaur",
    "img": "http://www.serebii.net/pokemongo/pokemon/001.png",
    "type": [
      "Grass",
      "Poison"
    ],
    "height": "0.71 m",
    "weight": "6.9 kg",
    "candy": "Bulbasaur Candy",
    "candy_count": 25,
    "egg": "2 km",
    "spawn_chance": 0.69,
let pokedex = readJson("data/definitive-guide/pokedex.json")
nbShow pokedex
shape: (1, 1)
pokemon
list[struct[17]]
[{1,"001","Bulbasaur","http://www.serebii.net/pokemongo/pokemon/001.png",["Grass", "Poison"],"0.71 m","6.9 kg","Bulbasaur Candy",25,"2 km",0.69,69.0,"20:00",[1.58],["Fire", "Ice", … "Psychic"],[{"002","Ivysaur"}, {"003","Venusaur"}],null}, {2,"002","Ivysaur","http://www.serebii.net/pokemongo/pokemon/002.png",["Grass", "Poison"],"0.99 m","13.0 kg","Bulbasaur Candy",100,"Not in Eggs",0.042,4.2,"07:00",[1.2, 1.6],["Fire", "Ice", … "Psychic"],[{"003","Venusaur"}],[{"001","Bulbasaur"}]}, … {151,"151","Mew","http://www.serebii.net/pokemongo/pokemon/151.png",["Psychic"],"0.41 m","4.0 kg","None",null,"Not in Eggs",0.0,0.0,"N/A",null,["Bug", "Ghost", "Dark"],null,null}]

So the frame has one row, with a list of structs. explode and unnest make it a table:

nbShow pokedex.explode("pokemon")
  .unnest("pokemon")
  .select("id", "name", "type", "height", "weight")
shape: (151, 5)
idnametypeheightweight
i64strlist[str]strstr
1"Bulbasaur"["Grass", "Poison"]"0.71 m""6.9 kg"
2"Ivysaur"["Grass", "Poison"]"0.99 m""13.0 kg"
3"Venusaur"["Grass", "Poison"]"2.01 m""100.0 kg"
4"Charmander"["Fire"]"0.61 m""8.5 kg"
5"Charmeleon"["Fire"]"1.09 m""19.0 kg"
……………
147"Dratini"["Dragon"]"1.80 m""3.3 kg"
148"Dragonair"["Dragon"]"3.99 m""16.5 kg"
149"Dragonite"["Dragon", "Flying"]"2.21 m""210.0 kg"
150"Mewtwo"["Psychic"]"2.01 m""122.0 kg"
151"Mew"["Psychic"]"0.41 m""4.0 kg"

NDJSON

Newline-delimited JSON has one object per line, here edits to Wikipedia:

echo readFile("data/definitive-guide/wikimedia.ndjson").splitLines[0][0 .. 300], "..."
{"$schema":"/mediawiki/recentchange/1.0.0","meta":{"uri":"https://en.wikipedia.org/wiki/EFL_Championship","request_id":"ea0541fb-4e72-4fc3-82f0-6c26651b2043","id":"0416300b-980c-45bb-b0a2-c9d7a9e2b7eb","dt":"2023-07-29T07:51:39Z","domain":"en.wikipedia.org","stream":"mediawiki.recentchange","topic":"...
let wikimedia = readNdjson("data/definitive-guide/wikimedia.ndjson")
nbShow wikimedia
shape: (100, 20)
$schemametaidtypenamespacetitletitle_urlcommenttimestampuserbotnotify_urlminorlengthrevisionserver_urlserver_nameserver_script_pathwikiparsedcomment
strstruct[9]i64stri64strstrstri64strboolstrboolstruct[2]struct[2]strstrstrstrstr
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/EFL_Championship","ea0541fb-4e72-4fc3-82f0-6c26651b2043","0416300b-980c-45bb-b0a2-c9d7a9e2b7eb","2023-07-29T07:51:39Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820784717}1659529639"edit"0"EFL Championship""https://en.wikipedia.org/wiki/…"/* League champions, runners-u…1690617099"87.12.215.232"false"https://en.wikipedia.org/w/ind…false{91108,91166}{1166824248,1167689309}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki""<span dir="auto"><span class="…
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/Lim_Sang-choon","01a0f468-7553-48db-b553-7ac392b2187c","97e4dc39-fb32-4774-9c9a-b2caea391c9e","2023-07-29T07:51:42Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820784731}1659529640"edit"0"Lim Sang-choon""https://en.wikipedia.org/wiki/…""1690617102"Preferwiki"false"https://en.wikipedia.org/w/ind…false{9807,10480}{1167689034,1167689310}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki"""
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/Higher","5f053899-a2ab-4dec-8e98-1d01cd86093d","0da41aa2-ceb6-443f-8a0a-0633f83de6ec","2023-07-29T07:51:44Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820784748}1659529642"edit"0"Higher""https://en.wikipedia.org/wiki/…"/* Albums */ add"1690617104"Ss112"false"https://en.wikipedia.org/w/ind…false{5452,5548}{1162509981,1167689312}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki""<span dir="auto"><span class="…
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/International_Poker_Rules","10c4886c-95f5-4cd2-8db9-333cb45f041b","af9cc405-26b2-485d-b20c-edd21b2a2a4c","2023-07-29T07:51:44Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820784763}1659529643"edit"0"International Poker Rules""https://en.wikipedia.org/wiki/…"Nominated for deletion; see [[…1690617104"Piotrus"false"https://en.wikipedia.org/w/ind…false{2452,2896}{1055827921,1167689313}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki""Nominated for deletion; see <a…
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/Abdul_Hamid_Khan_Bhashani","198e47ae-fa33-4059-970a-550536e7bc7c","2012e36f-9fa1-49dc-ba68-5946de740cd4","2023-07-29T07:51:45Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820784800}1659529653"edit"0"Abdul Hamid Khan Bhashani""https://en.wikipedia.org/wiki/…"Rescuing 1 sources and tagging…1690617105"InternetArchiveBot"true"https://en.wikipedia.org/w/ind…false{31503,31687}{1163358967,1167689318}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki""Rescuing 1 sources and tagging…
……………………………………………………
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/Havering_Residents_Association","d563edd1-2a19-491b-9604-aea1b7c57a67","f5b5b53d-8024-4c4d-810b-e3c04b8f2392","2023-07-29T07:53:58Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820788373}1659529961"edit"0"Havering Residents Association""https://en.wikipedia.org/wiki/…"/* 2018 election */ +map"1690617238"MRSC"false"https://en.wikipedia.org/w/ind…false{7590,7707}{1167689281,1167689476}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki""<span dir="auto"><span class="…
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/Olha_Kharlan","7caa4fe3-2ddf-4a57-b6d4-6eee505f5e49","b7b84f63-69f7-4317-82b2-df4a3e853723","2023-07-29T07:53:55Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820788404}1659529963"edit"0"Olha Kharlan""https://en.wikipedia.org/wiki/…"Ce"1690617235"2603:7000:2101:AA00:2C88:EF86:…false"https://en.wikipedia.org/w/ind…false{65119,65323}{1167666634,1167689477}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki""Ce"
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/Mukim_Kota_Batu","1032a354-1171-47a2-bdb3-cbcb78a070bf","a2b2601e-5adc-4ed2-b8fc-292d128009d7","2023-07-29T07:53:58Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820788418}1659529964"edit"0"Mukim Kota Batu""https://en.wikipedia.org/wiki/…""1690617238"Pangalau"false"https://en.wikipedia.org/w/ind…false{7178,7189}{1150066841,1167689474}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki"""
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/User:IDK1213safasx/sandbox","0f29a0a7-de5a-4197-a8dd-98b6a4eb5f6f","5c2219b5-7b3e-4720-944b-94afb5764b76","2023-07-29T07:53:59Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820788422}1659529965"edit"2"User:IDK1213safasx/sandbox""https://en.wikipedia.org/wiki/…""1690617239"94.101.29.27"false"https://en.wikipedia.org/w/ind…false{2122,2122}{1167356449,1167689478}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki"""
"/mediawiki/recentchange/1.0.0"{"https://en.wikipedia.org/wiki/List_of_bus_routes_in_London","04c7fd52-5689-4905-a208-9a92900e8efe","2eea26f7-4a02-454e-b597-82d3cb78f2ea","2023-07-29T07:53:54Z","en.wikipedia.org","mediawiki.recentchange","eqiad.mediawiki.recentchange",0,4820788423}1659529966"edit"0"List of bus routes in London""https://en.wikipedia.org/wiki/…"/* Non-TfL bus routes in Great…1690617234"Pedroperezhumberto"false"https://en.wikipedia.org/w/ind…false{155160,155098}{1167688737,1167689472}"https://en.wikipedia.org""en.wikipedia.org""/w""enwiki""<span dir="auto"><span class="…
nbShow wikimedia.rename({"id": "edit_id"})
  .unnest("meta")
  .select("timestamp", "title", "user", "comment")
shape: (100, 4)
timestamptitleusercomment
i64strstrstr
1690617099"EFL Championship""87.12.215.232""/* League champions, runners-u…
1690617102"Lim Sang-choon""Preferwiki"""
1690617104"Higher""Ss112""/* Albums */ add"
1690617104"International Poker Rules""Piotrus""Nominated for deletion; see [[…
1690617105"Abdul Hamid Khan Bhashani""InternetArchiveBot""Rescuing 1 sources and tagging…
…………
1690617238"Havering Residents Association""MRSC""/* 2018 election */ +map"
1690617235"Olha Kharlan""2603:7000:2101:AA00:2C88:EF86:…"Ce"
1690617238"Mukim Kota Batu""Pangalau"""
1690617239"User:IDK1213safasx/sandbox""94.101.29.27"""
1690617234"List of bus routes in London""Pedroperezhumberto""/* Non-TfL bus routes in Great…

Writing Data

CSV Format

let allStocks = readCsv("data/definitive-guide/all_stocks.csv")
allStocks.writeCsv("data/definitive-guide/all_stocks_copy.csv")

Parquet Format

allStocks.writeParquet("data/definitive-guide/all_stocks.parquet")
import nanuqbook
bookInit()

nbText: "# Reading and writing data"

attribution definitiveGuide(6, "Reading and Writing Data",
  "Data is read from `data/definitive-guide/` (penguins, the Pokédex JSON and the " &
  "Wikimedia NDJSON, from the book's repository); the `cat` cells show the start of the " &
  "files with Nim. Left out: other encodings than UTF-8 (Nanuq's `readCsv` has no " &
  "`encoding`), Excel, the stock-price files of the multiple-files section and the taxi " &
  "Parquet files (too big to ship), pandas and databases.")

nbText: """
Data comes from files, and goes back into them. This chapter reads CSV, JSON and NDJSON,
and writes CSV and Parquet.

## Reading CSV Files
"""

nbCode:
  import std/strutils
  echo readFile("data/definitive-guide/penguins.csv").splitLines[0 .. 4].join("\n")

tabs """
import polars as pl

penguins = pl.read_csv("data/definitive-guide/penguins.csv")
penguins
""":
  nbCode:
    import nanuq

    var penguins = readCsv("data/definitive-guide/penguins.csv")
    nbShow penguins

nbText: """
## Parsing Missing Values Correctly

The file writes missing values as `NA`, so the numeric columns with one came out as
strings. `null_values` says how missing values look:
"""

tabs """
penguins = pl.read_csv("data/definitive-guide/penguins.csv", null_values="NA")
penguins
""":
  nbCode:
    penguins = readCsv("data/definitive-guide/penguins.csv", nullValues = ["NA"])
    nbShow penguins

tabs """
penguins.null_count().transpose(
    include_header=True, column_names=["null_count"]
)
""":
  nbCode:
    nbShow penguins.select(all().nullCount).transpose(
      includeHeader = true, columnNames = ["null_count"])

nanuq """
Nanuq's frame `nullCount(column)` counts one column; for all of them, select
`all().nullCount`.
"""

nbText: """
## Reading JSON and NDJSON

### JSON

The Pokédex is one JSON object, with a list of Pokémon:
"""

nbCode:
  echo readFile("data/definitive-guide/pokedex.json").splitLines[0 .. 15].join("\n")

tabs """
pokedex = pl.read_json("data/definitive-guide/pokedex.json")
pokedex
""":
  nbCode:
    let pokedex = readJson("data/definitive-guide/pokedex.json")
    nbShow pokedex

nbText: "So the frame has one row, with a list of structs. `explode` and `unnest` make it a table:"

tabs """
(
    pokedex.explode("pokemon")
    .unnest("pokemon")
    .select("id", "name", "type", "height", "weight")
)
""":
  nbCode:
    nbShow pokedex.explode("pokemon")
      .unnest("pokemon")
      .select("id", "name", "type", "height", "weight")

nbText: """
### NDJSON

Newline-delimited JSON has one object per line, here edits to Wikipedia:
"""

nbCode:
  echo readFile("data/definitive-guide/wikimedia.ndjson").splitLines[0][0 .. 300], "..."

nanuq """
The book prints the first object with `pprint`; here the start of the first line is
enough.
"""

tabs """
wikimedia = pl.read_ndjson("data/definitive-guide/wikimedia.ndjson")
wikimedia
""":
  nbCode:
    let wikimedia = readNdjson("data/definitive-guide/wikimedia.ndjson")
    nbShow wikimedia

tabs """
(
    wikimedia.rename({"id": "edit_id"})
    .unnest("meta")
    .select("timestamp", "title", "user", "comment")
)
""":
  nbCode:
    nbShow wikimedia.rename({"id": "edit_id"})
      .unnest("meta")
      .select("timestamp", "title", "user", "comment")

nbText: """
## Writing Data

### CSV Format
"""

tabs """
all_stocks = pl.read_csv("data/definitive-guide/all_stocks.csv")
all_stocks.write_csv("data/definitive-guide/all_stocks_copy.csv")
""":
  nbCode:
    let allStocks = readCsv("data/definitive-guide/all_stocks.csv")
    allStocks.writeCsv("data/definitive-guide/all_stocks_copy.csv")

nanuq """
The book's `all_stocks` comes from the multiple-files section, left out here; the book
ships the result, `all_stocks.csv`, which both sides read and write to a copy.
"""

nbText: "### Parquet Format"

tabs """
all_stocks.write_parquet("data/definitive-guide/all_stocks.parquet")
""":
  nbCode:
    allStocks.writeParquet("data/definitive-guide/all_stocks.parquet")

bookSave()
Made with nimib and nimibook. Blocks marked "ran" were executed when this page was built.