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 |
+
|
15 |
+
import marimo
|
16 |
+
|
17 |
+
__generated_with = "0.15.2"
|
18 |
+
app = marimo.App(width="medium")
|
19 |
+
|
20 |
+
|
21 |
+
@app.cell(hide_code=True)
|
22 |
+
def _(mo):
|
23 |
+
mo.md(
|
24 |
+
r"""
|
25 |
+
# Loading Data
|
26 |
+
|
27 |
+
_By [etrotta](https://github.com/etrotta)._
|
28 |
+
|
29 |
+
This tutorial covers how to load data of varying formats and from different sources using [polars](https://docs.pola.rs/).
|
30 |
+
|
31 |
+
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 relevant links for users that need to connect with external sources, and explains how to deal with custom formats via plugins.
|
32 |
+
"""
|
33 |
+
)
|
34 |
+
return
|
35 |
+
|
36 |
+
|
37 |
+
@app.cell(hide_code=True)
|
38 |
+
def _(mo, pl):
|
39 |
+
df = pl.DataFrame(
|
40 |
+
[
|
41 |
+
{"format": "Parquet", "lazy": True, "notes": None},
|
42 |
+
{"format": "CSV", "lazy": True, "notes": None},
|
43 |
+
{
|
44 |
+
"format": "Databases",
|
45 |
+
"lazy": False,
|
46 |
+
"notes": "Requires another library as an Engine",
|
47 |
+
},
|
48 |
+
{
|
49 |
+
"format": "Excel",
|
50 |
+
"lazy": False,
|
51 |
+
"notes": "Requires another library as an Engine",
|
52 |
+
},
|
53 |
+
{
|
54 |
+
"format": "Newline-delimited JSON",
|
55 |
+
"lazy": True,
|
56 |
+
"notes": None,
|
57 |
+
},
|
58 |
+
{
|
59 |
+
"format": "Traditional JSON",
|
60 |
+
"lazy": False,
|
61 |
+
"notes": None,
|
62 |
+
},
|
63 |
+
{"format": "Arrow", "lazy": False, "notes": "You can load XML and HTML files via pandas"},
|
64 |
+
{"format": "Plugins", "lazy": True, "notes": "The most flexible, but takes some effort to implement"},
|
65 |
+
{"format": "Feather / IPC", "lazy": True, "notes": None},
|
66 |
+
{"format": "Avro", "lazy": False, "notes": None},
|
67 |
+
{"format": "Delta", "lazy": True, "notes": "No Lazy writing"},
|
68 |
+
{"format": "Iceberg", "lazy": True, "notes": "No Lazy writing"},
|
69 |
+
],
|
70 |
+
orient="rows",
|
71 |
+
)
|
72 |
+
mo.vstack(
|
73 |
+
[
|
74 |
+
mo.ui.table(df, label="Quick Reference", pagination=False),
|
75 |
+
"We will also use this table to demonstrate writing and reading to each format",
|
76 |
+
]
|
77 |
+
)
|
78 |
+
return (df,)
|
79 |
+
|
80 |
+
|
81 |
+
@app.cell(hide_code=True)
|
82 |
+
def _(mo):
|
83 |
+
mo.md(
|
84 |
+
r"""
|
85 |
+
## Parquet
|
86 |
+
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
|
87 |
+
"""
|
88 |
+
)
|
89 |
+
return
|
90 |
+
|
91 |
+
|
92 |
+
@app.cell
|
93 |
+
def _(df, folder, pl):
|
94 |
+
df.write_parquet(folder / "data.parquet") # Eager API - Writing to a file
|
95 |
+
_ = pl.read_parquet(folder / "data.parquet") # Eager API - Reading from a file
|
96 |
+
lz = pl.scan_parquet(folder / "data.parquet") # Lazy API - Reading from a file
|
97 |
+
lz.sink_parquet(folder / "data_copy.parquet") # Lazy API - Writing to a file
|
98 |
+
return (lz,)
|
99 |
+
|
100 |
+
|
101 |
+
@app.cell(hide_code=True)
|
102 |
+
def _(mo):
|
103 |
+
mo.md(
|
104 |
+
r"""
|
105 |
+
## CSV
|
106 |
+
A classic and common format that has been widely used for decades.
|
107 |
+
|
108 |
+
The API is almost identical 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.
|
109 |
+
"""
|
110 |
+
)
|
111 |
+
return
|
112 |
+
|
113 |
+
|
114 |
+
@app.cell
|
115 |
+
def _(df, folder, lz, pl):
|
116 |
+
lz.sink_csv(folder / "data.csv") # Lazy API - Writing to a file
|
117 |
+
df.write_csv(folder / "data_no_head.csv", include_header=False, separator=";") # Eager API - Writing to a file
|
118 |
+
|
119 |
+
_ = pl.scan_csv(folder / "data.csv") # Lazy API - Reading from a file
|
120 |
+
_ = pl.read_csv(folder / "data_no_head.csv", has_header=False, separator=";") # Eager API - Reading from a file
|
121 |
+
return
|
122 |
+
|
123 |
+
|
124 |
+
@app.cell(hide_code=True)
|
125 |
+
def _(mo):
|
126 |
+
mo.md(
|
127 |
+
r"""
|
128 |
+
## JSON
|
129 |
+
|
130 |
+
JavaScript Object Notation is somewhat commonly used for storing unstructed data, and extremely commonly used for API responses.
|
131 |
+
|
132 |
+
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`)
|
133 |
+
|
134 |
+
/// Note
|
135 |
+
|
136 |
+
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.
|
137 |
+
|
138 |
+
Polars supports Lists with variable length, Arrays with fixed length, and Structs with well defined fields, but not mappings with arbitrary keys.
|
139 |
+
|
140 |
+
You might want to transform data by unnesting structs and exploding lists after loading from complex JSON files.
|
141 |
+
"""
|
142 |
+
)
|
143 |
+
return
|
144 |
+
|
145 |
+
|
146 |
+
@app.cell
|
147 |
+
def _(df, folder, lz, pl):
|
148 |
+
# Newline Delimited JSON
|
149 |
+
lz.sink_ndjson(folder / "data.ndjson") # Lazy API - Writing to a file
|
150 |
+
df.write_ndjson(folder / "data.ndjson") # Eager API - Writing to a file
|
151 |
+
|
152 |
+
_ = pl.scan_ndjson(folder / "data.ndjson") # Lazy API - Reading from a file
|
153 |
+
_ = pl.read_ndjson(folder / "data.ndjson") # Eager API - Reading from a file
|
154 |
+
|
155 |
+
# Normal JSON
|
156 |
+
df.write_json(folder / "data.json") # Eager API - Writing to a file
|
157 |
+
_ = pl.read_json(folder / "data.json") # Eager API - Reading from a file
|
158 |
+
|
159 |
+
# Note that there are no Lazy methods for normal JSON files,
|
160 |
+
# 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
|
161 |
+
return
|
162 |
+
|
163 |
+
|
164 |
+
@app.cell(hide_code=True)
|
165 |
+
def _(mo):
|
166 |
+
mo.md(
|
167 |
+
r"""
|
168 |
+
## Databases
|
169 |
+
|
170 |
+
Polars doesn't supports any databases _directly_, but rather uses other libraries as Engines. Reading and writing to databases using polars methods 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.
|
171 |
+
|
172 |
+
You can also use other libraries with [arrow support](#arrow-support) or [polars plugins](#plugin-support) to read from databases before loading into polars, some of which support lazy reading.
|
173 |
+
|
174 |
+
Using the Arrow Database Connectivity SQLite support as an example:
|
175 |
+
"""
|
176 |
+
)
|
177 |
+
return
|
178 |
+
|
179 |
+
|
180 |
+
@app.cell
|
181 |
+
def _(df, folder, pl):
|
182 |
+
URI = "sqlite:///" + f"/{folder.resolve()}/db.sqlite"
|
183 |
+
df.write_database(table_name="quick_reference", connection=URI, engine="adbc", if_table_exists="replace")
|
184 |
+
|
185 |
+
query = """SELECT * FROM quick_reference WHERE format LIKE '%Database%'"""
|
186 |
+
|
187 |
+
pl.read_database_uri(query=query, uri=URI, engine="adbc")
|
188 |
+
return
|
189 |
+
|
190 |
+
|
191 |
+
@app.cell(hide_code=True)
|
192 |
+
def _(mo):
|
193 |
+
mo.md(
|
194 |
+
r"""
|
195 |
+
## Excel
|
196 |
+
|
197 |
+
From a performance perspective, we recommend using other formats if possible, such as Parquet or CSV files.
|
198 |
+
|
199 |
+
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.
|
200 |
+
"""
|
201 |
+
)
|
202 |
+
return
|
203 |
+
|
204 |
+
|
205 |
+
@app.cell(hide_code=True)
|
206 |
+
def _(mo):
|
207 |
+
mo.md(
|
208 |
+
r"""
|
209 |
+
## Others natively supported
|
210 |
+
|
211 |
+
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.
|
212 |
+
|
213 |
+
See https://docs.pola.rs/api/python/stable/reference/io.html for the full list of formats natively supported by Polars
|
214 |
+
"""
|
215 |
+
)
|
216 |
+
return
|
217 |
+
|
218 |
+
|
219 |
+
@app.cell(hide_code=True)
|
220 |
+
def _(mo):
|
221 |
+
mo.md(
|
222 |
+
r"""
|
223 |
+
## Arrow Support
|
224 |
+
|
225 |
+
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.
|
226 |
+
|
227 |
+
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.
|
228 |
+
"""
|
229 |
+
)
|
230 |
+
return
|
231 |
+
|
232 |
+
|
233 |
+
@app.cell
|
234 |
+
def _(df, folder, pd, pl):
|
235 |
+
# XML Example using `pandas` read_xml() and to_xml() methods
|
236 |
+
df.to_pandas().to_xml(folder / "data.xml")
|
237 |
+
pandas_df = pd.read_xml(folder / "data.xml")
|
238 |
+
_ = pl.from_pandas(pandas_df)
|
239 |
+
return
|
240 |
+
|
241 |
+
|
242 |
+
@app.cell(hide_code=True)
|
243 |
+
def _(mo):
|
244 |
+
mo.md(
|
245 |
+
r"""
|
246 |
+
## Plugin Support
|
247 |
+
|
248 |
+
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, or use other libraries that support polars via their own plugins such as DuckDB.
|
249 |
+
"""
|
250 |
+
)
|
251 |
+
return
|
252 |
+
|
253 |
+
|
254 |
+
@app.cell
|
255 |
+
def _(duckdb, folder):
|
256 |
+
# Requires duckdb >= 1.4.0
|
257 |
+
conn = duckdb.connect(folder / "db.sqlite")
|
258 |
+
conn.sql("SELECT * FROM quick_reference").pl(lazy=True)
|
259 |
+
return
|
260 |
+
|
261 |
+
|
262 |
+
@app.cell(hide_code=True)
|
263 |
+
def _(mo):
|
264 |
+
mo.md(
|
265 |
+
r"""
|
266 |
+
### Creating your own Plugin
|
267 |
+
|
268 |
+
The simplest form of plugins are essentially generators that yield DataFrames.
|
269 |
+
|
270 |
+
Without parsing filters you will be missing on performance improvements, but even just this can help improve your performance in many cases as it allows for polars to optimize the query and request data in batches as opposed to always loading everything in memory.
|
271 |
+
|
272 |
+
Below is a example plugin which just takes the product between multiple iterables, some highlights are that:
|
273 |
+
|
274 |
+
- You must use `register_io_source` for polars to create the LazyFrame which will consume the Generator
|
275 |
+
- You are expected to provide a Schema before the Generator starts
|
276 |
+
- - For many use cases the Plugin may be able to infer it, but you could also pass it explicitly to the plugin function
|
277 |
+
- Ideally you should parse some of the filters and column selectors to avoid unnecessary work, but it is possible to delegate that to polars after loading the data in order to keep it simpler (at the cost of efficiency)
|
278 |
+
|
279 |
+
Efficiently parsing the filter expressions is out of the scope for this notebook.
|
280 |
+
"""
|
281 |
+
)
|
282 |
+
return
|
283 |
+
|
284 |
+
|
285 |
+
@app.cell
|
286 |
+
def _(my_custom_input_plugin):
|
287 |
+
my_custom_input_plugin(int, range(3), range(5))
|
288 |
+
return
|
289 |
+
|
290 |
+
|
291 |
+
@app.cell
|
292 |
+
def _(my_custom_input_plugin, pl):
|
293 |
+
my_custom_input_plugin(bool, [True, False], [True, False]).with_columns(
|
294 |
+
(pl.col("A") & pl.col("B")).alias("AND"),
|
295 |
+
(pl.col("A") & pl.col("B")).not_().alias("NAND"),
|
296 |
+
(pl.col("A") | pl.col("B")).alias("OR"),
|
297 |
+
(pl.col("A") ^ pl.col("B")).alias("XOR"),
|
298 |
+
).collect()
|
299 |
+
return
|
300 |
+
|
301 |
+
|
302 |
+
@app.cell
|
303 |
+
def _(Iterator, get_positional_names, itertools, pl, register_io_source):
|
304 |
+
def my_custom_input_plugin(dtype, *iterables) -> pl.LazyFrame:
|
305 |
+
schema = pl.Schema({key: dtype for key in get_positional_names(len(iterables))})
|
306 |
+
|
307 |
+
def source_generator(
|
308 |
+
with_columns: list[str] | None,
|
309 |
+
predicate: pl.Expr | None,
|
310 |
+
n_rows: int | None,
|
311 |
+
batch_size: int | None,
|
312 |
+
) -> Iterator[pl.DataFrame]:
|
313 |
+
"""
|
314 |
+
Generator function that creates the source.
|
315 |
+
This function will be registered as IO source.
|
316 |
+
"""
|
317 |
+
if batch_size is None:
|
318 |
+
batch_size = 100
|
319 |
+
if n_rows is not None:
|
320 |
+
batch_size = min(batch_size, n_rows)
|
321 |
+
|
322 |
+
generator = itertools.product(*iterables)
|
323 |
+
while n_rows is None or n_rows > 0:
|
324 |
+
rows = []
|
325 |
+
try:
|
326 |
+
while len(rows) < batch_size:
|
327 |
+
rows.append(next(generator))
|
328 |
+
except StopIteration:
|
329 |
+
n_rows = -1
|
330 |
+
|
331 |
+
df = pl.from_records(rows, schema=schema, orient="row")
|
332 |
+
if n_rows is not None:
|
333 |
+
n_rows -= df.height
|
334 |
+
batch_size = min(batch_size, n_rows)
|
335 |
+
|
336 |
+
# If we would make a performant reader, we would not read these
|
337 |
+
# columns at all.
|
338 |
+
if with_columns is not None:
|
339 |
+
df = df.select(with_columns)
|
340 |
+
|
341 |
+
# If the source supports predicate pushdown, the expression can be parsed
|
342 |
+
# to skip rows/groups.
|
343 |
+
if predicate is not None:
|
344 |
+
df = df.filter(predicate)
|
345 |
+
|
346 |
+
yield df
|
347 |
+
|
348 |
+
return register_io_source(io_source=source_generator, schema=schema)
|
349 |
+
return (my_custom_input_plugin,)
|
350 |
+
|
351 |
+
|
352 |
+
@app.cell(hide_code=True)
|
353 |
+
def _(mo):
|
354 |
+
mo.md(
|
355 |
+
r"""
|
356 |
+
### DuckDB
|
357 |
+
|
358 |
+
As demonstrated above, in addition to Arrow interoperability support, [DuckDB](https://duckdb.org/) also has added support for loading query results into a polars DataFrame or LazyFrame via a polars plugin.
|
359 |
+
|
360 |
+
You can read more about polars and duckdb integrations in
|
361 |
+
|
362 |
+
- https://docs.pola.rs/user-guide/ecosystem/#duckdb
|
363 |
+
- https://duckdb.org/docs/stable/guides/python/polars.html
|
364 |
+
|
365 |
+
You can learn more about DuckDB in the marimo course about it as well, including Marimo SQL related features
|
366 |
+
"""
|
367 |
+
)
|
368 |
+
return
|
369 |
+
|
370 |
+
|
371 |
+
@app.cell
|
372 |
+
def _():
|
373 |
+
# Amazing if you need of features not yet supported by Polars such as geospatial data
|
374 |
+
duckdb_query = """
|
375 |
+
SELECT
|
376 |
+
id,
|
377 |
+
name,
|
378 |
+
ST_X(geometry) as longitude,
|
379 |
+
ST_Y(geometry) as latitude
|
380 |
+
FROM locations
|
381 |
+
"""
|
382 |
+
return (duckdb_query,)
|
383 |
+
|
384 |
+
|
385 |
+
@app.cell
|
386 |
+
def _(duckdb_conn, duckdb_query):
|
387 |
+
# Eager (default):
|
388 |
+
duckdb_conn.sql(duckdb_query).pl()
|
389 |
+
return
|
390 |
+
|
391 |
+
|
392 |
+
@app.cell
|
393 |
+
def _(duckdb_conn, duckdb_query):
|
394 |
+
# Lazy (requires >= 1.4.0):
|
395 |
+
duckdb_conn.sql(duckdb_query).pl(lazy=True)
|
396 |
+
return
|
397 |
+
|
398 |
+
|
399 |
+
@app.cell(hide_code=True)
|
400 |
+
def _(mo):
|
401 |
+
mo.md(
|
402 |
+
r"""
|
403 |
+
## Hive Partitions
|
404 |
+
|
405 |
+
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
|
406 |
+
).
|
407 |
+
|
408 |
+
Even without using partitions, many methods also support glob patterns to read multiple files in the same folder such as `scan_csv(folder / "*.csv")`
|
409 |
+
"""
|
410 |
+
)
|
411 |
+
return
|
412 |
+
|
413 |
+
|
414 |
+
@app.cell
|
415 |
+
def _(df, folder, pl):
|
416 |
+
df.write_parquet(str((folder / "hive").resolve()) + "/", partition_by=["lazy"])
|
417 |
+
_ = pl.scan_parquet(str((folder / "hive").resolve()) + "/").filter(pl.col("lazy").eq(True)).collect()
|
418 |
+
|
419 |
+
print(*(folder / "hive").rglob("*.parquet"), sep="\n")
|
420 |
+
return
|
421 |
+
|
422 |
+
|
423 |
+
@app.cell(hide_code=True)
|
424 |
+
def _(mo):
|
425 |
+
mo.md(
|
426 |
+
r"""
|
427 |
+
# Reading from the Cloud
|
428 |
+
|
429 |
+
Polars also has support for reading public and private datasets from multiple websites
|
430 |
+
and cloud storage solutions.
|
431 |
+
|
432 |
+
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.
|
433 |
+
"""
|
434 |
+
)
|
435 |
+
return
|
436 |
+
|
437 |
+
|
438 |
+
@app.cell(hide_code=True)
|
439 |
+
def _(mo):
|
440 |
+
mo.md(
|
441 |
+
r"""
|
442 |
+
## Arbitrary web sites
|
443 |
+
|
444 |
+
You can load files from nearly any website just by using a HTTPS URL, as long as it is not locked behind authorization.
|
445 |
+
"""
|
446 |
+
)
|
447 |
+
return
|
448 |
+
|
449 |
+
|
450 |
+
@app.cell(disabled=True)
|
451 |
+
def _():
|
452 |
+
# df = pl.read_csv('https://example.com/file.csv')
|
453 |
+
return
|
454 |
+
|
455 |
+
|
456 |
+
@app.cell(hide_code=True)
|
457 |
+
def _(mo):
|
458 |
+
mo.md(
|
459 |
+
r"""
|
460 |
+
## Hugging Face & Kaggle Datasets
|
461 |
+
|
462 |
+
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
|
463 |
+
|
464 |
+
Read more: [Hugging Face](https://docs.pola.rs/user-guide/io/hugging-face/), [Kaggle](https://github.com/Kaggle/kagglehub/blob/main/README.md#kaggledatasetadapterpolars)
|
465 |
+
"""
|
466 |
+
)
|
467 |
+
return
|
468 |
+
|
469 |
+
|
470 |
+
@app.cell(disabled=True)
|
471 |
+
def _():
|
472 |
+
# df = pl.read_parquet('hf://datasets/username/dataset/*.parquet')
|
473 |
+
return
|
474 |
+
|
475 |
+
|
476 |
+
@app.cell(hide_code=True)
|
477 |
+
def _(mo):
|
478 |
+
mo.md(
|
479 |
+
r"""
|
480 |
+
## Cloud Storage - AWS S3, Azure Blob Storage, Google Cloud Storage
|
481 |
+
|
482 |
+
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.
|
483 |
+
|
484 |
+
Runnable examples are not included in this Notebook as it would require setting up authentication, but the disabled cell below shows an example using Azure.
|
485 |
+
"""
|
486 |
+
)
|
487 |
+
return
|
488 |
+
|
489 |
+
|
490 |
+
@app.cell(disabled=True)
|
491 |
+
def _(adlfs, df, os, pl):
|
492 |
+
fs = adlfs.AzureBlobFileSystem(connection_string=os.environ["AZURE_STORAGE_CONNECTION_STRING"])
|
493 |
+
destination = f"abfs://{os.environ['AZURE_CONTAINER_NAME']}/file.parquet"
|
494 |
+
|
495 |
+
# Writing
|
496 |
+
with fs.open(destination, mode="wb") as f:
|
497 |
+
df.write_parquet(f)
|
498 |
+
|
499 |
+
# Reading
|
500 |
+
pl.read_parquet(
|
501 |
+
destination, storage_options={"account_name": os.environ["AZURE_STORAGE_ACCOUNT"], "use_azure_cli": "True"}
|
502 |
+
)
|
503 |
+
|
504 |
+
# Deleting
|
505 |
+
fs.delete(destination)
|
506 |
+
|
507 |
+
# If you get an error saying that the account does not exists, double check you logged in the correct account and subscription via `az login`
|
508 |
+
return
|
509 |
+
|
510 |
+
|
511 |
+
@app.cell(hide_code=True)
|
512 |
+
def _(mo):
|
513 |
+
mo.md(
|
514 |
+
r"""
|
515 |
+
# Multiplexing
|
516 |
+
|
517 |
+
You can also split a query into multiple sinks via [multiplexing](https://docs.pola.rs/user-guide/lazy/multiplexing/), to avoid reading multiple times, repeating the same operations for each sink or collecting intermediary results into memory.
|
518 |
+
"""
|
519 |
+
)
|
520 |
+
return
|
521 |
+
|
522 |
+
|
523 |
+
@app.cell
|
524 |
+
def _(folder, lz, pl):
|
525 |
+
lz2 = lz.with_columns(pl.col(pl.String).str.to_uppercase())
|
526 |
+
lz3 = lz.with_columns(pl.col(pl.String).str.to_lowercase())
|
527 |
+
|
528 |
+
# Collecting multiple LazyFrames into memory
|
529 |
+
_df, _df2, _df3 = pl.collect_all([lz, lz2, lz3])
|
530 |
+
|
531 |
+
# Sinking multiple LazyFrames into different destinations
|
532 |
+
sinks = [
|
533 |
+
lz.sink_csv(folder / "data_1.csv", lazy=True),
|
534 |
+
lz2.sink_csv(folder / "data_2.csv", lazy=True),
|
535 |
+
lz3.sink_csv(folder / "data_3.csv", lazy=True),
|
536 |
+
]
|
537 |
+
_ = pl.collect_all(sinks)
|
538 |
+
return (sinks,)
|
539 |
+
|
540 |
+
|
541 |
+
@app.cell(hide_code=True)
|
542 |
+
def _(mo):
|
543 |
+
mo.md(
|
544 |
+
r"""
|
545 |
+
# Async Execution
|
546 |
+
|
547 |
+
Polars also has experimental support for running lazy queries in `async` mode, letting you `await` operations inside of async functions.
|
548 |
+
"""
|
549 |
+
)
|
550 |
+
return
|
551 |
+
|
552 |
+
|
553 |
+
@app.cell
|
554 |
+
async def _(lz):
|
555 |
+
await lz.collect_async()
|
556 |
+
return
|
557 |
+
|
558 |
+
|
559 |
+
@app.cell
|
560 |
+
async def _(folder, lz, pl, sinks):
|
561 |
+
# If you want to write to a file, use `lz.sink_format(lazy=True)` followed by `...collect_async()` or `pl.collect_all_async(...)`
|
562 |
+
_ = await lz.sink_csv(folder / "data_from_async.csv", lazy=True).collect_async()
|
563 |
+
_ = await pl.collect_all_async(sinks)
|
564 |
+
return
|
565 |
+
|
566 |
+
|
567 |
+
@app.cell(hide_code=True)
|
568 |
+
def _(mo):
|
569 |
+
mo.md(
|
570 |
+
r"""
|
571 |
+
## Conclusion
|
572 |
+
As you have seen, polars makes it easy to work with a variety of formats and different data sources.
|
573 |
+
|
574 |
+
From natively supported formats such as Parquet and CSV files, to using other libraries as an intermediary for XML or geospatial data, and plugins for newly emerging or proprietary formats, as long as your data can fit in a table then odds are you can turn it into a polars DataFrame.
|
575 |
+
|
576 |
+
Combined with loading directly from remote sources, including public data platforms such as Hugging Face and Kaggle as well as private data in your cloud, you can import datasets for almost anything you can imagine.
|
577 |
+
"""
|
578 |
+
)
|
579 |
+
return
|
580 |
+
|
581 |
+
|
582 |
+
@app.cell(hide_code=True)
|
583 |
+
def _(mo):
|
584 |
+
mo.md(
|
585 |
+
r"""
|
586 |
+
## Utilities
|
587 |
+
Imports, utility functions and alike used through the Notebook
|
588 |
+
"""
|
589 |
+
)
|
590 |
+
return
|
591 |
+
|
592 |
+
|
593 |
+
@app.cell
|
594 |
+
def _():
|
595 |
+
import marimo as mo
|
596 |
+
return (mo,)
|
597 |
+
|
598 |
+
|
599 |
+
@app.cell(disabled=True)
|
600 |
+
def _():
|
601 |
+
# You may need to install `fsspec ` and `adlfs ` beyond the dependencies included in the notebook
|
602 |
+
import os
|
603 |
+
import adlfs
|
604 |
+
return adlfs, os
|
605 |
+
|
606 |
+
|
607 |
+
@app.cell
|
608 |
+
def _():
|
609 |
+
import pathlib
|
610 |
+
import tempfile
|
611 |
+
|
612 |
+
folder = pathlib.Path(tempfile.mkdtemp())
|
613 |
+
folder
|
614 |
+
return (folder,)
|
615 |
+
|
616 |
+
|
617 |
+
@app.cell
|
618 |
+
def _():
|
619 |
+
import math
|
620 |
+
import string
|
621 |
+
import itertools
|
622 |
+
from typing import Iterator
|
623 |
+
return Iterator, itertools, string
|
624 |
+
|
625 |
+
|
626 |
+
@app.cell
|
627 |
+
def _():
|
628 |
+
import polars as pl
|
629 |
+
import pandas as pd
|
630 |
+
from polars.io.plugins import register_io_source
|
631 |
+
import duckdb
|
632 |
+
return duckdb, pd, pl, register_io_source
|
633 |
+
|
634 |
+
|
635 |
+
@app.cell
|
636 |
+
def _(itertools, string):
|
637 |
+
def get_positional_names(count: int) -> list[str]:
|
638 |
+
out = []
|
639 |
+
size = 0
|
640 |
+
while True:
|
641 |
+
size += 1 # number of characters in each column name
|
642 |
+
for column in itertools.product(*itertools.repeat(string.ascii_uppercase, size)):
|
643 |
+
if len(out) >= count:
|
644 |
+
return out
|
645 |
+
out.append("".join(column))
|
646 |
+
return (get_positional_names,)
|
647 |
+
|
648 |
+
|
649 |
+
@app.cell
|
650 |
+
def _(duckdb):
|
651 |
+
# Connect to an ephemeral in-memory DuckDB database
|
652 |
+
duckdb_conn = duckdb.connect(":memory:")
|
653 |
+
|
654 |
+
# Install and load the spatial extension for geometry support
|
655 |
+
duckdb_conn.install_extension("spatial")
|
656 |
+
duckdb_conn.load_extension("spatial")
|
657 |
+
|
658 |
+
# Create a table with geometry column
|
659 |
+
duckdb_conn.sql("""
|
660 |
+
CREATE TABLE locations (
|
661 |
+
id INTEGER,
|
662 |
+
name VARCHAR,
|
663 |
+
geometry GEOMETRY
|
664 |
+
)
|
665 |
+
""")
|
666 |
+
|
667 |
+
# Insert some sample data with geometry points
|
668 |
+
duckdb_conn.sql("""
|
669 |
+
INSERT INTO locations VALUES
|
670 |
+
(1, 'New York', ST_Point(-74.0059, 40.7128)),
|
671 |
+
(2, 'Los Angeles', ST_Point(-118.2437, 34.0522)),
|
672 |
+
(3, 'Chicago', ST_Point(-87.6298, 41.8781)),
|
673 |
+
(4, 'Houston', ST_Point(-95.3698, 29.7604)),
|
674 |
+
(5, 'Phoenix', ST_Point(-112.0740, 33.4484))
|
675 |
+
""")
|
676 |
+
return (duckdb_conn,)
|
677 |
+
|
678 |
+
|
679 |
+
if __name__ == "__main__":
|
680 |
+
app.run()
|