etrotta commited on
Commit
b894464
·
1 Parent(s): a50306f

Add Loading Data Notebook

Browse files
Files changed (1) hide show
  1. polars/03_loading_data.py +372 -0
polars/03_loading_data.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = [
4
+ # "adbc-driver-sqlite==1.6.0",
5
+ # "lxml==5.4.0",
6
+ # "marimo",
7
+ # "pandas==2.2.3",
8
+ # "polars==1.30.0",
9
+ # "pyarrow==20.0.0",
10
+ # "sqlalchemy==2.0.41",
11
+ # ]
12
+ # ///
13
+
14
+ import marimo
15
+
16
+ __generated_with = "0.13.6"
17
+ app = marimo.App(width="medium")
18
+
19
+
20
+ @app.cell(hide_code=True)
21
+ def _(mo):
22
+ mo.md(
23
+ r"""
24
+ # Loading Data
25
+
26
+ _By [etrotta](https://github.com/etrotta)._
27
+
28
+ This tutorial covers how to load data of varying formats and from different sources using [polars](https://docs.pola.rs/).
29
+
30
+ It includes examples of how to load and write to a variety of formats, shows how to convert data from other libraries to support formats not supported directly by polars, includes relevants links for users that need to connect with external sources, and explains how to deal with custom formats via plugins.
31
+ """
32
+ )
33
+ return
34
+
35
+
36
+ @app.cell(hide_code=True)
37
+ def _(mo, pl):
38
+ df = pl.DataFrame(
39
+ [
40
+ {"format": "Parquet", "lazy": True, "notes": None},
41
+ {"format": "CSV", "lazy": True, "notes": None},
42
+ {
43
+ "format": "Databases",
44
+ "lazy": False,
45
+ "notes": "Requires another library as an Engine",
46
+ },
47
+ {
48
+ "format": "Excel",
49
+ "lazy": False,
50
+ "notes": "Requires another library as an Engine",
51
+ },
52
+ {
53
+ "format": "Newline-delimited JSON",
54
+ "lazy": True,
55
+ "notes": None,
56
+ },
57
+ {
58
+ "format": "Traditional JSON",
59
+ "lazy": False,
60
+ "notes": None,
61
+ },
62
+ {"format": "Arrow", "lazy": False, "notes": "You can load XML and HTML files via pandas"},
63
+ {"format": "Plugins", "lazy": True, "notes": "The most flexibile, but takes some effort to implement"},
64
+ {"format": "Feather / IPC", "lazy": True, "notes": None},
65
+ {"format": "Avro", "lazy": False, "notes": None},
66
+ {"format": "Delta", "lazy": True, "notes": "No Lazy writing"},
67
+ {"format": "Iceberg", "lazy": True, "notes": "No Lazy writing"},
68
+ ],
69
+ orient="rows",
70
+ )
71
+ mo.vstack(
72
+ [
73
+ mo.ui.table(df, label="Quick Reference", pagination=False),
74
+ "We will also use this table to demonstrate writing and reading to each format",
75
+ ]
76
+ )
77
+ return (df,)
78
+
79
+
80
+ @app.cell(hide_code=True)
81
+ def _(mo):
82
+ mo.md(
83
+ r"""
84
+ ## Parquet
85
+ Parquet is a popular format for storing tabular data based on the Arrow memory spec, it is a great default and you'll find a lot of datasets already using it in sites like HuggingFace
86
+ """
87
+ )
88
+ return
89
+
90
+
91
+ @app.cell
92
+ def _(df, folder, pl):
93
+ df.write_parquet(folder / "data.parquet") # Eager API - Writing to a file
94
+ _ = pl.read_parquet(folder / "data.parquet") # Eager API - Reading from a file
95
+ lz = pl.scan_parquet(folder / "data.parquet") # Lazy API - Reading from a file
96
+ lz.sink_parquet(folder / "data_copy.parquet") # Lazy API - Writing to a file
97
+ return (lz,)
98
+
99
+
100
+ @app.cell(hide_code=True)
101
+ def _(mo):
102
+ mo.md(
103
+ r"""
104
+ ## CSV
105
+ A classic and common format that has been widely used for decades.
106
+
107
+ The API is almost identic to Parquet - You can just replace `parquet` by `csv` and it will work with the default settings, but polars also allows for you to customize some settings such as the delimiter and quoting rules.
108
+ """
109
+ )
110
+ return
111
+
112
+
113
+ @app.cell
114
+ def _(df, folder, lz, pl):
115
+ lz.sink_csv(folder / "data.csv") # Lazy API - Writing to a file
116
+ df.write_csv(folder / "data_no_head.csv", include_header=False, separator=",") # Eager API - Writing to a file
117
+
118
+ _ = pl.scan_csv(folder / "data.csv") # Lazy API - Reading from a file
119
+ _ = pl.read_csv(folder / "data_no_head.csv", has_header=False, separator=";") # Eager API - Reading from a file
120
+ return
121
+
122
+
123
+ @app.cell(hide_code=True)
124
+ def _(mo):
125
+ mo.md(
126
+ r"""
127
+ ## JSON
128
+
129
+ JavaScript Object Notation is somewhat commonly used for storing unstructed data, and extremely commonly used for API responses.
130
+
131
+ For large datasets you'll frequently see a variation in which each line in the file defines one separate object, called "Newline delimited JSON" (`ndjson`) or "JSON Lines" (`jsonl`)
132
+
133
+ /// Note
134
+
135
+ It's a lot more common to find Nested data in JSON than in other formats, but other formats such as Parquet also support nested datatypes.
136
+
137
+ Polars supports Lists with variable length, Arrays with fixed length, and Structs with well defined fields, but not mappings with arbitrary keys.
138
+
139
+ You might want to transform data using by unnested structs and exploding lists after loading from complex JSON files.
140
+ """
141
+ )
142
+ return
143
+
144
+
145
+ @app.cell
146
+ def _(df, folder, lz, pl):
147
+ # Newline Delimited JSON
148
+ lz.sink_ndjson(folder / "data.ndjson") # Lazy API - Writing to a file
149
+ df.write_ndjson(folder / "data.ndjson") # Eager API - Writing to a file
150
+
151
+ _ = pl.scan_ndjson(folder / "data.ndjson") # Lazy API - Reading from a file
152
+ _ = pl.read_ndjson(folder / "data.ndjson") # Eager API - Reading from a file
153
+
154
+ # Normal JSON
155
+ df.write_json(folder / "data_no_head.json") # Eager API - Writing to a file
156
+ _ = pl.read_json(folder / "data_no_head.json") # Eager API - Reading from a file
157
+
158
+ # Note that there are no Lazy methods for normal JSON files,
159
+ # either use NDJSON instead or use `lz.collect().write_json()` to collect into memory before writing, and `pl.read_json().lazy()` to read into memory before operating in lazy mode
160
+ return
161
+
162
+
163
+ @app.cell(hide_code=True)
164
+ def _(mo):
165
+ mo.md(
166
+ r"""
167
+ ## Databases
168
+
169
+ Polars doesn't supports any _directly_, but rather uses other libraries as Engines. Reading and writing to databases does not supports Lazy execution, but you may pass an SQL Query for the database to pre-filter the data before reaches polars. See the [User Guide](https://docs.pola.rs/user-guide/io/database) for more details.
170
+
171
+ Using the Arrow Database Connectivity SQLite support as an example:
172
+ """
173
+ )
174
+ return
175
+
176
+
177
+ @app.cell
178
+ def _(df, folder, pl):
179
+ URI = "sqlite:///" + f"/{folder.resolve()}/db.sqlite"
180
+ df.write_database(table_name="quick_reference", connection=URI, engine="adbc", if_table_exists="replace")
181
+
182
+ query = """SELECT * FROM quick_reference WHERE format LIKE '%Database%'"""
183
+
184
+ pl.read_database_uri(query=query, uri=URI, engine="adbc")
185
+ return
186
+
187
+
188
+ @app.cell(hide_code=True)
189
+ def _(mo):
190
+ mo.md(
191
+ r"""
192
+ ## Excel
193
+
194
+ From a performance perspective, we recommend using other formats if possible, such as Parquet or CSV files.
195
+
196
+ Similarly to Databases, polars doesn't supports it natively but rather uses other libraries as Engines. See the [User Guide](https://docs.pola.rs/user-guide/io/excel) if you need to use it.
197
+ """
198
+ )
199
+ return
200
+
201
+
202
+ @app.cell(hide_code=True)
203
+ def _(mo):
204
+ mo.md(
205
+ r"""
206
+ ## Others natively supported
207
+
208
+ If you understood the above examples, then all other formats should feel familiar - the core API is the same for all formats, `read` and `write` for the Eager API or `scan` and `sink` for the lazy API.
209
+
210
+ See https://docs.pola.rs/api/python/stable/reference/io.html for the full list of formats natively supported by Polars
211
+ """
212
+ )
213
+ return
214
+
215
+
216
+ @app.cell(hide_code=True)
217
+ def _(mo):
218
+ mo.md(
219
+ r"""
220
+ ## Arrow Support
221
+
222
+ You can convert Arrow compatible data from other libraries such as `pandas`, `duckdb` or `pyarrow` to polars DataFrames and vice-versa, much of the time without even having to copy data.
223
+
224
+ This allows for you to use other libraries to load data in formats not support by polars, then convert the dataframe in-memory to polars.
225
+ """
226
+ )
227
+ return
228
+
229
+
230
+ @app.cell
231
+ def _(df, folder, pd, pl):
232
+ # XML Example using `pandas` read_xml() and to_xml() methods
233
+ df.to_pandas().to_xml(folder / "data.xml")
234
+ pandas_df = pd.read_xml(folder / "data.xml")
235
+ _ = pl.from_pandas(pandas_df)
236
+ return
237
+
238
+
239
+ @app.cell(hide_code=True)
240
+ def _(mo):
241
+ mo.md(
242
+ r"""
243
+ ## Plugin Support
244
+
245
+ You can also write [IO Plugins](https://docs.pola.rs/user-guide/plugins/io_plugins/) for Polars in order to support any format you need.
246
+
247
+ TODO UPDATE THIS SECTION
248
+
249
+ - Consider whenever we want to include a full example
250
+ - Link an example of a real production-grade plugin
251
+ """
252
+ )
253
+ return
254
+
255
+
256
+ @app.cell(hide_code=True)
257
+ def _(mo):
258
+ mo.md(
259
+ r"""
260
+
261
+ ## Hive Partitions
262
+
263
+ There is also support for [Hive](https://docs.pola.rs/user-guide/io/hive/) partitioned data, but parts of the API are still unstable (may change in future polars versions
264
+ ).
265
+
266
+ Even without using partitions, many methods also support glob patterns to read multiple files in the same folder such as `scan_csv(folder / "*.csv")`
267
+ """
268
+ )
269
+ return
270
+
271
+
272
+ @app.cell
273
+ def _(df, folder, pl):
274
+ df.write_parquet(str((folder / "hive").resolve()) + "/", partition_by=["lazy"])
275
+ _ = pl.scan_parquet(str((folder / "hive").resolve()) + "/").filter(pl.col("lazy").eq(True)).collect()
276
+
277
+ print(*(folder / "hive").rglob("*.parquet"), sep="\n")
278
+ return
279
+
280
+
281
+ @app.cell(hide_code=True)
282
+ def _(mo):
283
+ mo.md(
284
+ r"""
285
+ # Reading from the Cloud
286
+
287
+ Polars also has support for reading public and private datasets from multiple websites
288
+ and cloud storage solutions.
289
+
290
+ If you must (re)use the same file many times in the same machine you may want to manually download it then load from your local file system instead to avoid re-downloading though, or download and write to disk only if the file does not exists.
291
+ """
292
+ )
293
+ return
294
+
295
+
296
+ @app.cell(hide_code=True)
297
+ def _(mo):
298
+ mo.md(
299
+ r"""
300
+ ## Arbitrary web sites
301
+
302
+ You can load files from nearly any website just by using a HTTPS URL, as long as it is not locked behind authorization.
303
+ """
304
+ )
305
+ return
306
+
307
+
308
+ @app.cell(disabled=True)
309
+ def _():
310
+ # df = pl.read_csv('https://example.com/file.csv')
311
+ return
312
+
313
+
314
+ @app.cell(hide_code=True)
315
+ def _(mo):
316
+ mo.md(
317
+ r"""
318
+ ## Hugging Face & Kaggle Datasets
319
+
320
+ Look for polars inside of dropdowns such as "Use this dataset" in Hugging Face or "Code" in Kaggle, and oftentimes you'll get a snippet to load data directly into a dataframe you can use
321
+
322
+ Read more: [Hugging Face](https://docs.pola.rs/user-guide/io/hugging-face/), [Kaggle](https://github.com/Kaggle/kagglehub/blob/main/README.md#kaggledatasetadapterpolars)
323
+ """
324
+ )
325
+ return
326
+
327
+
328
+ @app.cell(disabled=True)
329
+ def _():
330
+ # df = pl.read_parquet('hf://datasets/username/dataset/*.parquet')
331
+ return
332
+
333
+
334
+ @app.cell(hide_code=True)
335
+ def _(mo):
336
+ mo.md(
337
+ r"""
338
+ ## Cloud Storage - AWS S3, Azure Blob Storage, Google Cloud Storage
339
+
340
+ The API is the same for all three storage providers, check the [User Guide](https://docs.pola.rs/user-guide/io/cloud-storage/) if you need of any of them.
341
+
342
+ Examples are not included in this Notebook as it would require setting up authentication.
343
+ """
344
+ )
345
+ return
346
+
347
+
348
+ @app.cell
349
+ def _():
350
+ import marimo as mo
351
+ return (mo,)
352
+
353
+
354
+ @app.cell
355
+ def _():
356
+ import pathlib
357
+ import tempfile
358
+
359
+ folder = pathlib.Path(tempfile.mkdtemp())
360
+ folder
361
+ return (folder,)
362
+
363
+
364
+ @app.cell
365
+ def _():
366
+ import polars as pl
367
+ import pandas as pd
368
+ return pd, pl
369
+
370
+
371
+ if __name__ == "__main__":
372
+ app.run()