Raine Hoang commited on
Commit
7a41a9e
·
1 Parent(s): 3fb7b66

added dataframes lesson notebook to polars section

Browse files
Files changed (1) hide show
  1. polars/02_dataframes.py +503 -0
polars/02_dataframes.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import marimo
2
+
3
+ __generated_with = "0.12.5"
4
+ app = marimo.App(width="medium")
5
+
6
+
7
+ @app.cell
8
+ def _():
9
+ import marimo as mo
10
+ import polars as pl
11
+ import numpy as np
12
+ import pandas as pd
13
+ return mo, np, pd, pl
14
+
15
+
16
+ @app.cell(hide_code=True)
17
+ def _(mo):
18
+ mo.md(
19
+ r"""
20
+ # DataFrames
21
+ Author: Raine Hoang
22
+
23
+ In this tutorial, we will go over the central data structure for structured data, DataFrames. There are a multitude of packages that work with DataFrames, but we will be focusing on the way Polars uses them the different options it provides.
24
+
25
+ **Note**: The following tutorial has been adapted from the Polars [documentation](https://docs.pola.rs/api/python/stable/reference/dataframe/index.html).
26
+ """
27
+ )
28
+ return
29
+
30
+
31
+ @app.cell(hide_code=True)
32
+ def _(mo):
33
+ mo.md(
34
+ """
35
+ ## Defining a DataFrame
36
+
37
+ At the most basic level, all that you need to do in order to create a DataFrame in Polars is to use the .DataFrame() method and pass in some data into the data parameter. However, there are restrictions as to what exactly you can pass into this method.
38
+ """
39
+ )
40
+ return
41
+
42
+
43
+ @app.cell(hide_code=True)
44
+ def _(mo):
45
+ mo.md(r"""### What Can Be a DataFrame?""")
46
+ return
47
+
48
+
49
+ @app.cell(hide_code=True)
50
+ def _(mo):
51
+ mo.md(
52
+ r"""
53
+ There are 5 data types that can be converted into a DataFrame.
54
+
55
+ 1. Dictionary
56
+ 2. Sequence
57
+ 3. NumPy Array
58
+ 4. Series
59
+ 5. Pandas DataFrame
60
+ """
61
+ )
62
+ return
63
+
64
+
65
+ @app.cell(hide_code=True)
66
+ def _(mo):
67
+ mo.md(
68
+ r"""
69
+ #### Dictionary
70
+
71
+ Dictionaries are structures that store data as key:value pairs. Let's say we have the following dictionary:
72
+ """
73
+ )
74
+ return
75
+
76
+
77
+ @app.cell
78
+ def _():
79
+ dct_data = {"col1": [1, 2, 3, 4], "col2": ["a", "b", "c", "d"], "col3": [1.2, 4.2, 6.4, 3.7]}
80
+ dct_data
81
+ return (dct_data,)
82
+
83
+
84
+ @app.cell(hide_code=True)
85
+ def _(mo):
86
+ mo.md(r"""In order to convert this dictionary into a DataFrame, we simply need to pass it into the data parameter in the .DataFrame() method like so.""")
87
+ return
88
+
89
+
90
+ @app.cell
91
+ def _(dct_data, pl):
92
+ dct_df = pl.DataFrame(data = dct_data)
93
+ dct_df
94
+ return (dct_df,)
95
+
96
+
97
+ @app.cell(hide_code=True)
98
+ def _(mo):
99
+ mo.md(
100
+ r"""
101
+ In this case, Polars turned each of the lists in the dictionary into a column in the DataFrame.
102
+
103
+ The other data structures will follow a similar pattern when converting them to DataFrames.
104
+ """
105
+ )
106
+ return
107
+
108
+
109
+ @app.cell(hide_code=True)
110
+ def _(mo):
111
+ mo.md(
112
+ r"""
113
+ ##### Sequence
114
+
115
+ Sequences are data structures that contain collections of items, which can be accessed using its index. Examples of sequences are lists, tuples, and strings. We will be using a list of lists in order to demonstrate how to convert a sequence in a DataFrame.
116
+ """
117
+ )
118
+ return
119
+
120
+
121
+ @app.cell
122
+ def _():
123
+ seq_data = [[1, 2, 3, 4], ["a", "b", "c", "d"], [1.2, 4.2, 6.4, 3.7]]
124
+ seq_data
125
+ return (seq_data,)
126
+
127
+
128
+ @app.cell
129
+ def _(pl, seq_data):
130
+ seq_df = pl.DataFrame(data = seq_data)
131
+ seq_df
132
+ return (seq_df,)
133
+
134
+
135
+ @app.cell(hide_code=True)
136
+ def _(mo):
137
+ mo.md(r"""Notice that since we didn't specify the column names, Polars automatically named them "column_0", "column_1", and "column_2". Later, we will show you how to specify the names of the columns.""")
138
+ return
139
+
140
+
141
+ @app.cell(hide_code=True)
142
+ def _(mo):
143
+ mo.md(
144
+ r"""
145
+ ##### NumPy Array
146
+
147
+ NumPy arrays are considered a sequence of items that can also be accessed using its index. An important thing to note is that all of the items in an array must have the same data type.
148
+ """
149
+ )
150
+ return
151
+
152
+
153
+ @app.cell
154
+ def _(np):
155
+ arr_data = np.array([np.array([1, 2, 3, 4]), np.array(["a", "b", "c", "d"]), np.array([1.2, 4.2, 6.4, 3.7])])
156
+ arr_data
157
+ return (arr_data,)
158
+
159
+
160
+ @app.cell
161
+ def _(arr_data, pl):
162
+ arr_df = pl.DataFrame(data = arr_data)
163
+ arr_df
164
+ return (arr_df,)
165
+
166
+
167
+ @app.cell(hide_code=True)
168
+ def _(mo):
169
+ mo.md(r"""Notice that each inner array is a row in the DataFrame, not a column like the previous methods discussed. Later, we will go over how to tell Polars if we the information in the data structure to be presented as rows or columns.""")
170
+ return
171
+
172
+
173
+ @app.cell(hide_code=True)
174
+ def _(mo):
175
+ mo.md(
176
+ r"""
177
+ ##### Series
178
+
179
+ Series are a way to store a single column in a DataFrame and all entries in a series must have the same data type. You can combine these series together to form one DataFrame.
180
+ """
181
+ )
182
+ return
183
+
184
+
185
+ @app.cell
186
+ def _(pl):
187
+ pl_series = [pl.Series([1, 2, 3, 4]), pl.Series(["a", "b", "c", "d"]), pl.Series([1.2, 4.2, 6.4, 3.7])]
188
+ pl_series
189
+ return (pl_series,)
190
+
191
+
192
+ @app.cell
193
+ def _(pl, pl_series):
194
+ series_df = pl.DataFrame(data = pl_series)
195
+ series_df
196
+ return (series_df,)
197
+
198
+
199
+ @app.cell(hide_code=True)
200
+ def _(mo):
201
+ mo.md(
202
+ r"""
203
+ ##### Pandas DataFrame
204
+
205
+ Another popular package that utilizes DataFrames is pandas. By passing in a pandas DataFrame into .DataFrame(), you can easily convert it into a Polars DataFrame.
206
+ """
207
+ )
208
+ return
209
+
210
+
211
+ @app.cell
212
+ def _(dct_data, pd):
213
+ # Creates a DataFrame from a dictionary using pandas package
214
+ pd_df = pd.DataFrame(data = dct_data)
215
+
216
+ pd_df
217
+ return (pd_df,)
218
+
219
+
220
+ @app.cell
221
+ def _(pd_df, pl):
222
+ # Takes pandas DataFrame and converts it into Polars DataFrame
223
+ pl_df = pl.DataFrame(data = pd_df)
224
+
225
+ pl_df
226
+ return (pl_df,)
227
+
228
+
229
+ @app.cell(hide_code=True)
230
+ def _(mo):
231
+ mo.md(r"""Now that we've looked over what can be converted into a DataFrame and the basics of it, let's look at the structure of the DataFrame.""")
232
+ return
233
+
234
+
235
+ @app.cell
236
+ def _(mo):
237
+ mo.md(
238
+ r"""
239
+ ## DataFrame Structure
240
+
241
+ Let's recall one of the DataFrames we defined earlier.
242
+ """
243
+ )
244
+ return
245
+
246
+
247
+ @app.cell
248
+ def _(dct_df):
249
+ dct_df
250
+ return
251
+
252
+
253
+ @app.cell(hide_code=True)
254
+ def _(mo):
255
+ mo.md(r"""We can see that this DataFrame has 4 rows and 3 columns as indicated by the text beneath the DataFrame. Each column has a name that can be used to access the data within that column. In this case, the names are: "col1", "col2", and "col3". Below the column name, there is text that indicates the data type stored within that column. "col1" has the text "i64" underneath its name, meaning that that column stores integers. "col2" stores strings as seen by the "str" under the column name. Finally, "col3" stores floats as it has "f64" under the column name. Polars will automatically assume the data types stored in each column, but we will go over a way to specify it later in this tutorial. Each column can only hold one data type at a time, so you can't have a string and an integer in the same column.""")
256
+ return
257
+
258
+
259
+ @app.cell(hide_code=True)
260
+ def _(mo):
261
+ mo.md(
262
+ r"""
263
+ ## Parameters
264
+
265
+ On top of the "data" parameter, there are 6 additional parameters you can specify:
266
+
267
+ 1. schema
268
+ 2. schema_overrides
269
+ 3. strict
270
+ 4. orient
271
+ 5. infer_schema_length
272
+ 6. nan_to_null
273
+ """
274
+ )
275
+ return
276
+
277
+
278
+ @app.cell(hide_code=True)
279
+ def _(mo):
280
+ mo.md(
281
+ r"""
282
+ #### Schema
283
+
284
+ Let's recall the DataFrame we created using a sequence.
285
+ """
286
+ )
287
+ return
288
+
289
+
290
+ @app.cell
291
+ def _(seq_df):
292
+ seq_df
293
+ return
294
+
295
+
296
+ @app.cell(hide_code=True)
297
+ def _(mo):
298
+ mo.md(r"""We can see that the column names and data type were inferred by Polars. The schema parameter allows us to specify the column names and data type we want for each column. There are 3 ways you can use this parameter. The first way involves using a dictionary to define the following key value pair: column name:data type.""")
299
+ return
300
+
301
+
302
+ @app.cell
303
+ def _(pl, seq_data):
304
+ pl.DataFrame(seq_data, schema = {"integers": pl.Int16, "strings": pl.String, "floats": pl.Float32})
305
+ return
306
+
307
+
308
+ @app.cell(hide_code=True)
309
+ def _(mo):
310
+ mo.md(r"""You can also do this using a list of (column name, data type) pairs instead of a dictionary.""")
311
+ return
312
+
313
+
314
+ @app.cell
315
+ def _(pl, seq_data):
316
+ pl.DataFrame(seq_data, schema = [("integers", pl.Int16), ("strings", pl.String), ("floats", pl.Float32)])
317
+ return
318
+
319
+
320
+ @app.cell(hide_code=True)
321
+ def _(mo):
322
+ mo.md(r"""Notice how both the column names and the data type (text underneath the column name) is different from the original `seq_df`. If you only wanted to specify the column names and let Polars assume the data type, you can do so using a list of column names.""")
323
+ return
324
+
325
+
326
+ @app.cell
327
+ def _(pl, seq_data):
328
+ pl.DataFrame(seq_data, schema = ["integers", "strings", "floats"])
329
+ return
330
+
331
+
332
+ @app.cell(hide_code=True)
333
+ def _(mo):
334
+ mo.md(r"""The text under the column names is different from the previous two DataFrames we created since we didn't explicitly tell Polars what data type we wanted in each column.""")
335
+ return
336
+
337
+
338
+ @app.cell(hide_code=True)
339
+ def _(mo):
340
+ mo.md(
341
+ r"""
342
+ #### Schema_Overrides
343
+
344
+ If you only wanted to specify the data type of specific columns and let Polars infer the rest, you can use the schema_overrides parameter for that. This parameter requires that you pass in a dictionary where the key value pair is column name:data type. Unlike the schema parameter, the column name must match the name already present in the DataFrame as that is how Polars will identify which column you want to specify the data type. If you use a column name that doesn't already exist, Polars won't be able to change the data type.
345
+ """
346
+ )
347
+ return
348
+
349
+
350
+ @app.cell
351
+ def _(pl, seq_data):
352
+ pl.DataFrame(seq_data, schema_overrides = {"column_0": pl.Int16})
353
+ return
354
+
355
+
356
+ @app.cell(hide_code=True)
357
+ def _(mo):
358
+ mo.md(
359
+ r"""
360
+ Notice here that only the data type in the first column changed while Polars inferred the rest.
361
+
362
+ It is important to note that if you only use the schema_overrides parameter, you are limited to how much you can change the data type. In the example above, we were able to change the data type from int32 to int16 without any further parameters since the data type is still an integer. However, if we wanted to change the first column to be a string, we would get an error as Polars has already strictly set the schema to only take in integer values.
363
+ """
364
+ )
365
+ return
366
+
367
+
368
+ @app.cell
369
+ def _(pl, seq_data):
370
+ pl.DataFrame(seq_data, schema_overrides = {"column_0": pl.String})
371
+ return
372
+
373
+
374
+ @app.cell(hide_code=True)
375
+ def _(mo):
376
+ mo.md(r"""If we wanted to use schema_override to completely change the data type of the column, we need an additional parameter: strict.""")
377
+ return
378
+
379
+
380
+ @app.cell
381
+ def _(mo):
382
+ mo.md(
383
+ r"""
384
+ #### Strict
385
+
386
+ The strict parameter allows you to specify if you want a column's data type to be enforced with flexibility or not. When set to `True`, Polars will raise an error if there is a data type that doesn't match the data type the column is expecting. It will not attempt to type cast it to the correct data type as Polars prioritizes that all the data can be converted without any loss or error. When set to `False`, Polars will attempt to type cast the data into the data type the column wants. If it is unable to successfully convert the data type, the value will be replaced with a null value.
387
+ """
388
+ )
389
+ return
390
+
391
+
392
+ @app.cell(hide_code=True)
393
+ def _(mo):
394
+ mo.md(r"""Let's see an example of what happens when strict is set to `True`. The cell below should show an error.""")
395
+ return
396
+
397
+
398
+ @app.cell
399
+ def _(pl):
400
+ data = [[1, "a", 2]]
401
+
402
+ pl.DataFrame(data = data, strict = True)
403
+ return (data,)
404
+
405
+
406
+ @app.cell
407
+ def _(mo):
408
+ mo.md(r"""Now let's try setting strict to `False`.""")
409
+ return
410
+
411
+
412
+ @app.cell
413
+ def _(pl, seq_data):
414
+ pl.DataFrame(seq_data, schema_overrides = {"column_0": pl.String}, strict = False)
415
+ return
416
+
417
+
418
+ @app.cell(hide_code=True)
419
+ def _(mo):
420
+ mo.md(r"""Since we allowed for Polars to change the schema by setting strict to `False`, we were able to cast the first column to be strings.""")
421
+ return
422
+
423
+
424
+ @app.cell(hide_code=True)
425
+ def _(mo):
426
+ mo.md(
427
+ """
428
+ #### Orient
429
+
430
+ Let's recall the DataFrame we made by using an array and the data used to make it.
431
+ """
432
+ )
433
+ return
434
+
435
+
436
+ @app.cell
437
+ def _(arr_data):
438
+ arr_data
439
+ return
440
+
441
+
442
+ @app.cell
443
+ def _(arr_df):
444
+ arr_df
445
+ return
446
+
447
+
448
+ @app.cell(hide_code=True)
449
+ def _(mo):
450
+ mo.md(r"""Notice how Polars decided to make each inner array a row in the DataFrame. If we wanted to make it so that each inner array was a column instead of a row, all we would need to do is pass `"col"` into the orient parameter.""")
451
+ return
452
+
453
+
454
+ @app.cell
455
+ def _(arr_data, pl):
456
+ pl.DataFrame(data = arr_data, orient = "col")
457
+ return
458
+
459
+
460
+ @app.cell(hide_code=True)
461
+ def _(mo):
462
+ mo.md(r"""If we wanted to do the opposite, then we pass `"row"` into the orient parameter.""")
463
+ return
464
+
465
+
466
+ @app.cell
467
+ def _(seq_df):
468
+ seq_df
469
+ return
470
+
471
+
472
+ @app.cell
473
+ def _(pl, seq_data):
474
+ pl.DataFrame(data = seq_data, orient = "row")
475
+ return
476
+
477
+
478
+ @app.cell(hide_code=True)
479
+ def _(mo):
480
+ mo.md(
481
+ r"""
482
+ #### Infer_Schema_Length
483
+
484
+ Without setting the schema ourselves, Polars uses the data provided to infer the data types of the columns. It does this by looking at each of the rows in the data provided. You can specify to Polars how many rows to look at by using the infer_schema_length parameter. For example, if you were to set this parameter to 5, then Polars would use the first 5 rows to infer the schema.
485
+ """
486
+ )
487
+ return
488
+
489
+
490
+ @app.cell(hide_code=True)
491
+ def _(mo):
492
+ mo.md(
493
+ r"""
494
+ #### NaN_To_Null
495
+
496
+ If there are np.nan values in the data, you can convert them to null values by setting the nan_to_null parameter to `True`.
497
+ """
498
+ )
499
+ return
500
+
501
+
502
+ if __name__ == "__main__":
503
+ app.run()