Srihari Thyagarajan commited on
Commit
88e688e
·
unverified ·
2 Parent(s): 68f7784 96688d4

Merge pull request #97 from Jystine/main

Browse files
Files changed (1) hide show
  1. polars/02_dataframes.py +534 -0
polars/02_dataframes.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "marimo",
5
+ # "numpy==2.2.5",
6
+ # "pandas==2.2.3",
7
+ # "polars==1.29.0",
8
+ # ]
9
+ # ///
10
+
11
+ import marimo
12
+
13
+ __generated_with = "0.13.10"
14
+ app = marimo.App()
15
+
16
+
17
+ @app.cell(hide_code=True)
18
+ def _(mo):
19
+ mo.md(
20
+ r"""
21
+ # DataFrames
22
+ Author: [*Raine Hoang*](https://github.com/Jystine)
23
+
24
+ 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.
25
+
26
+ /// Note
27
+ The following tutorial has been adapted from the Polars [documentation](https://docs.pola.rs/api/python/stable/reference/dataframe/index.html).
28
+ """
29
+ )
30
+ return
31
+
32
+
33
+ @app.cell(hide_code=True)
34
+ def _(mo):
35
+ mo.md(
36
+ """
37
+ ## Defining a DataFrame
38
+
39
+ 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.
40
+ """
41
+ )
42
+ return
43
+
44
+
45
+ @app.cell(hide_code=True)
46
+ def _(mo):
47
+ mo.md(r"""### What Can Be a DataFrame?""")
48
+ return
49
+
50
+
51
+ @app.cell(hide_code=True)
52
+ def _(mo):
53
+ mo.md(
54
+ r"""
55
+ There are [5 data types](https://github.com/pola-rs/polars/blob/py-1.29.0/py-polars/polars/dataframe/frame.py#L197) that can be converted into a DataFrame.
56
+
57
+ 1. Dictionary
58
+ 2. Sequence
59
+ 3. NumPy Array
60
+ 4. Series
61
+ 5. Pandas DataFrame
62
+ """
63
+ )
64
+ return
65
+
66
+
67
+ @app.cell(hide_code=True)
68
+ def _(mo):
69
+ mo.md(
70
+ r"""
71
+ #### Dictionary
72
+
73
+ Dictionaries are structures that store data as `key:value` pairs. Let's say we have the following dictionary:
74
+ """
75
+ )
76
+ return
77
+
78
+
79
+ @app.cell
80
+ def _():
81
+ dct_data = {"col1": [1, 2, 3, 4], "col2": ["a", "b", "c", "d"], "col3": [1.2, 4.2, 6.4, 3.7]}
82
+ dct_data
83
+ return (dct_data,)
84
+
85
+
86
+ @app.cell(hide_code=True)
87
+ def _(mo):
88
+ 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.""")
89
+ return
90
+
91
+
92
+ @app.cell
93
+ def _(dct_data, pl):
94
+ dct_df = pl.DataFrame(data = dct_data)
95
+ dct_df
96
+ return (dct_df,)
97
+
98
+
99
+ @app.cell(hide_code=True)
100
+ def _(mo):
101
+ mo.md(
102
+ r"""
103
+ In this case, Polars turned each of the lists in the dictionary into a column in the DataFrame.
104
+
105
+ The other data structures will follow a similar pattern when converting them to DataFrames.
106
+ """
107
+ )
108
+ return
109
+
110
+
111
+ @app.cell(hide_code=True)
112
+ def _(mo):
113
+ mo.md(
114
+ r"""
115
+ ##### Sequence
116
+
117
+ 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.
118
+ """
119
+ )
120
+ return
121
+
122
+
123
+ @app.cell
124
+ def _():
125
+ seq_data = [[1, 2, 3, 4], ["a", "b", "c", "d"], [1.2, 4.2, 6.4, 3.7]]
126
+ seq_data
127
+ return (seq_data,)
128
+
129
+
130
+ @app.cell
131
+ def _(pl, seq_data):
132
+ seq_df = pl.DataFrame(data = seq_data)
133
+ seq_df
134
+ return (seq_df,)
135
+
136
+
137
+ @app.cell(hide_code=True)
138
+ def _(mo):
139
+ 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.""")
140
+ return
141
+
142
+
143
+ @app.cell(hide_code=True)
144
+ def _(mo):
145
+ mo.md(
146
+ r"""
147
+ ##### NumPy Array
148
+
149
+ 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.
150
+ """
151
+ )
152
+ return
153
+
154
+
155
+ @app.cell
156
+ def _(np):
157
+ 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])])
158
+ arr_data
159
+ return (arr_data,)
160
+
161
+
162
+ @app.cell
163
+ def _(arr_data, pl):
164
+ arr_df = pl.DataFrame(data = arr_data)
165
+ arr_df
166
+ return (arr_df,)
167
+
168
+
169
+ @app.cell(hide_code=True)
170
+ def _(mo):
171
+ 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.""")
172
+ return
173
+
174
+
175
+ @app.cell(hide_code=True)
176
+ def _(mo):
177
+ mo.md(
178
+ r"""
179
+ ##### Series
180
+
181
+ 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.
182
+ """
183
+ )
184
+ return
185
+
186
+
187
+ @app.cell
188
+ def _(pl):
189
+ pl_series = [pl.Series([1, 2, 3, 4]), pl.Series(["a", "b", "c", "d"]), pl.Series([1.2, 4.2, 6.4, 3.7])]
190
+ pl_series
191
+ return (pl_series,)
192
+
193
+
194
+ @app.cell
195
+ def _(pl, pl_series):
196
+ series_df = pl.DataFrame(data = pl_series)
197
+ series_df
198
+ return
199
+
200
+
201
+ @app.cell(hide_code=True)
202
+ def _(mo):
203
+ mo.md(
204
+ r"""
205
+ ##### Pandas DataFrame
206
+
207
+ 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.
208
+ """
209
+ )
210
+ return
211
+
212
+
213
+ @app.cell
214
+ def _(dct_data, pd):
215
+ # Creates a DataFrame from a dictionary using pandas package
216
+ pd_df = pd.DataFrame(data = dct_data)
217
+
218
+ pd_df
219
+ return (pd_df,)
220
+
221
+
222
+ @app.cell
223
+ def _(pd_df, pl):
224
+ # Takes pandas DataFrame and converts it into Polars DataFrame
225
+ pl_df = pl.DataFrame(data = pd_df)
226
+
227
+ pl_df
228
+ return
229
+
230
+
231
+ @app.cell(hide_code=True)
232
+ def _(mo):
233
+ 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.""")
234
+ return
235
+
236
+
237
+ @app.cell(hide_code=True)
238
+ def _(mo):
239
+ mo.md(
240
+ r"""
241
+ ## DataFrame Structure
242
+
243
+ Let's recall one of the DataFrames we defined earlier.
244
+ """
245
+ )
246
+ return
247
+
248
+
249
+ @app.cell
250
+ def _(dct_df):
251
+ dct_df
252
+ return
253
+
254
+
255
+ @app.cell(hide_code=True)
256
+ def _(mo):
257
+ 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.""")
258
+ return
259
+
260
+
261
+ @app.cell(hide_code=True)
262
+ def _(mo):
263
+ mo.md(
264
+ r"""
265
+ ## Parameters
266
+
267
+ On top of the "data" parameter, there are 6 additional parameters you can specify:
268
+
269
+ 1. schema
270
+ 2. schema_overrides
271
+ 3. strict
272
+ 4. orient
273
+ 5. infer_schema_length
274
+ 6. nan_to_null
275
+ """
276
+ )
277
+ return
278
+
279
+
280
+ @app.cell(hide_code=True)
281
+ def _(mo):
282
+ mo.md(
283
+ r"""
284
+ #### Schema
285
+
286
+ Let's recall the DataFrame we created using a sequence.
287
+ """
288
+ )
289
+ return
290
+
291
+
292
+ @app.cell
293
+ def _(seq_df):
294
+ seq_df
295
+ return
296
+
297
+
298
+ @app.cell(hide_code=True)
299
+ def _(mo):
300
+ 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.""")
301
+ return
302
+
303
+
304
+ @app.cell
305
+ def _(pl, seq_data):
306
+ pl.DataFrame(seq_data, schema = {"integers": pl.Int16, "strings": pl.String, "floats": pl.Float32})
307
+ return
308
+
309
+
310
+ @app.cell(hide_code=True)
311
+ def _(mo):
312
+ mo.md(r"""You can also do this using a list of (column name, data type) pairs instead of a dictionary.""")
313
+ return
314
+
315
+
316
+ @app.cell
317
+ def _(pl, seq_data):
318
+ pl.DataFrame(seq_data, schema = [("integers", pl.Int16), ("strings", pl.String), ("floats", pl.Float32)])
319
+ return
320
+
321
+
322
+ @app.cell(hide_code=True)
323
+ def _(mo):
324
+ 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.""")
325
+ return
326
+
327
+
328
+ @app.cell
329
+ def _(pl, seq_data):
330
+ pl.DataFrame(seq_data, schema = ["integers", "strings", "floats"])
331
+ return
332
+
333
+
334
+ @app.cell(hide_code=True)
335
+ def _(mo):
336
+ 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.""")
337
+ return
338
+
339
+
340
+ @app.cell(hide_code=True)
341
+ def _(mo):
342
+ mo.md(
343
+ r"""
344
+ #### Schema_Overrides
345
+
346
+ 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.
347
+ """
348
+ )
349
+ return
350
+
351
+
352
+ @app.cell
353
+ def _(pl, seq_data):
354
+ pl.DataFrame(seq_data, schema_overrides = {"column_0": pl.Int16})
355
+ return
356
+
357
+
358
+ @app.cell(hide_code=True)
359
+ def _(mo):
360
+ mo.md(
361
+ r"""
362
+ Notice here that only the data type in the first column changed while Polars inferred the rest.
363
+
364
+ 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.
365
+ """
366
+ )
367
+ return
368
+
369
+
370
+ @app.cell
371
+ def _(pl, seq_data):
372
+ try:
373
+ pl.DataFrame(seq_data, schema_overrides = {"column_0": pl.String})
374
+ except Exception as e:
375
+ print(f"Error: {e}")
376
+ return
377
+
378
+
379
+ @app.cell(hide_code=True)
380
+ def _(mo):
381
+ 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.""")
382
+ return
383
+
384
+
385
+ @app.cell(hide_code=True)
386
+ def _(mo):
387
+ mo.md(
388
+ r"""
389
+ #### Strict
390
+
391
+ 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.
392
+ """
393
+ )
394
+ return
395
+
396
+
397
+ @app.cell(hide_code=True)
398
+ def _(mo):
399
+ mo.md(r"""Let's see an example of what happens when strict is set to `True`. The cell below should show an error.""")
400
+ return
401
+
402
+
403
+ @app.cell
404
+ def _(pl):
405
+ data = [[1, "a", 2]]
406
+
407
+ try:
408
+ pl.DataFrame(data = data, strict = True)
409
+ except Exception as e:
410
+ print(f"Error: {e}")
411
+ return
412
+
413
+
414
+ @app.cell(hide_code=True)
415
+ def _(mo):
416
+ mo.md(r"""Now let's try setting strict to `False`.""")
417
+ return
418
+
419
+
420
+ @app.cell
421
+ def _(pl, seq_data):
422
+ pl.DataFrame(seq_data, schema_overrides = {"column_0": pl.String}, strict = False)
423
+ return
424
+
425
+
426
+ @app.cell(hide_code=True)
427
+ def _(mo):
428
+ 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.""")
429
+ return
430
+
431
+
432
+ @app.cell(hide_code=True)
433
+ def _(mo):
434
+ mo.md(
435
+ """
436
+ #### Orient
437
+
438
+ Let's recall the DataFrame we made by using an array and the data used to make it.
439
+ """
440
+ )
441
+ return
442
+
443
+
444
+ @app.cell
445
+ def _(arr_data):
446
+ arr_data
447
+ return
448
+
449
+
450
+ @app.cell
451
+ def _(arr_df):
452
+ arr_df
453
+ return
454
+
455
+
456
+ @app.cell(hide_code=True)
457
+ def _(mo):
458
+ 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.""")
459
+ return
460
+
461
+
462
+ @app.cell
463
+ def _(arr_data, pl):
464
+ pl.DataFrame(data = arr_data, orient = "col")
465
+ return
466
+
467
+
468
+ @app.cell(hide_code=True)
469
+ def _(mo):
470
+ mo.md(r"""If we wanted to do the opposite, then we pass `"row"` into the orient parameter.""")
471
+ return
472
+
473
+
474
+ @app.cell
475
+ def _(seq_df):
476
+ seq_df
477
+ return
478
+
479
+
480
+ @app.cell
481
+ def _(pl, seq_data):
482
+ pl.DataFrame(data = seq_data, orient = "row")
483
+ return
484
+
485
+
486
+ @app.cell(hide_code=True)
487
+ def _(mo):
488
+ mo.md(
489
+ r"""
490
+ #### Infer_Schema_Length
491
+
492
+ 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.
493
+ """
494
+ )
495
+ return
496
+
497
+
498
+ @app.cell(hide_code=True)
499
+ def _(mo):
500
+ mo.md(
501
+ r"""
502
+ #### NaN_To_Null
503
+
504
+ 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`.
505
+ """
506
+ )
507
+ return
508
+
509
+
510
+ @app.cell(hide_code=True)
511
+ def _(mo):
512
+ mo.md(
513
+ r"""
514
+ ## Summary
515
+
516
+ DataFrames are a useful data structure that can be used to organize and perform additional analysis on your data. In this notebook, we have learned how to define DataFrames, what can be a DataFrame, the structure of it, and additional parameters you can set while creating it.
517
+
518
+ In order to create a DataFrame, you pass your data into the .DataFrame() method through the data parameter. The data you pass through must be either a dictionary, sequence, array, series, or pandas DataFrame. Once defined, the DataFrame will separate the data into different columns and the data within the column must have the same data type. There exists additional parameters besides data that allows you to further customize the ending DataFrame. Some examples of these are orient, strict, and infer_schema_length.
519
+ """
520
+ )
521
+ return
522
+
523
+
524
+ @app.cell
525
+ def _():
526
+ import marimo as mo
527
+ import polars as pl
528
+ import numpy as np
529
+ import pandas as pd
530
+ return mo, np, pd, pl
531
+
532
+
533
+ if __name__ == "__main__":
534
+ app.run()