Spaces:
Sleeping
Sleeping
fix typos, read file from hugging face and my own formatting nitpicks
Browse files- polars/11_missing_data.py +32 -30
polars/11_missing_data.py
CHANGED
|
@@ -99,7 +99,7 @@ def _(df):
|
|
| 99 |
return
|
| 100 |
|
| 101 |
|
| 102 |
-
@app.cell
|
| 103 |
def _(mo):
|
| 104 |
mo.md(
|
| 105 |
r"""
|
|
@@ -108,10 +108,10 @@ def _(mo):
|
|
| 108 |
To filter in polars, you'll typically use `df.filter(expression)` or `df.remove(expression)` methods.
|
| 109 |
|
| 110 |
Filter will only keep rows in which the expression evaluates to True.
|
| 111 |
-
It will remove not only rows in which it
|
| 112 |
|
| 113 |
Remove will only remove rows in which the expression evaluates to True.
|
| 114 |
-
It will keep rows in which it
|
| 115 |
"""
|
| 116 |
)
|
| 117 |
return
|
|
@@ -133,7 +133,7 @@ def _(df, pl):
|
|
| 133 |
def _(mo):
|
| 134 |
mo.md(
|
| 135 |
r"""
|
| 136 |
-
You may also be tempted to use `== None` or `!= None`, but
|
| 137 |
|
| 138 |
You can use `.eq_missing()` or `.ne_missing()` methods if you want to be strict about it, but there are also `.is_null()` and `.is_not_null()` methods you can use.
|
| 139 |
"""
|
|
@@ -163,6 +163,8 @@ def _(mo):
|
|
| 163 |
You can also fill in the values with constants, calculations or by consulting external data sources.
|
| 164 |
|
| 165 |
Be careful not to treat estimated or guessed values as if they a ground truth however, otherwise you may end up making conclusions about a reality that does not exists.
|
|
|
|
|
|
|
| 166 |
"""
|
| 167 |
)
|
| 168 |
return
|
|
@@ -177,7 +179,6 @@ def _(df, mo, pl):
|
|
| 177 |
guesstimates = mo.ui.data_editor(
|
| 178 |
guesstimates,
|
| 179 |
editable_columns=["name"],
|
| 180 |
-
label="Let's guess some values to fill in nulls, then try giving names to the animals with `null` by editing the cells",
|
| 181 |
)
|
| 182 |
guesstimates
|
| 183 |
return (guesstimates,)
|
|
@@ -201,7 +202,7 @@ def _(mo):
|
|
| 201 |
- you could just drop rows with values missing in any columns or a subset of them with `df.drop_nulls()`, but for most cases you'll want to be more careful about it
|
| 202 |
- take into consideration whenever you want to preserve null values or remove them when choosing between `df.filter()` or `df.remove()`
|
| 203 |
- if you don't want to propagate null values, use `_missing` variations of methods such as `eq` vs `eq_missing`
|
| 204 |
-
- you may want to fill in missing values based on calculations via `fill_null`, or manually edit the data based on external documents
|
| 205 |
|
| 206 |
You can also refer to the polars [User Guide](https://docs.pola.rs/user-guide/expressions/missing-data/) more more information.
|
| 207 |
|
|
@@ -220,7 +221,7 @@ def _(mo):
|
|
| 220 |
We will be using a dataset from `alertario` about the weather in Rio de Janeiro, originally available in Google Big Query under `datario.clima_pluviometro`. What you need to know about it:
|
| 221 |
|
| 222 |
- Contains multiple stations covering the Municipality of Rio de Janeiro
|
| 223 |
-
- Measures the precipitation as
|
| 224 |
- We filtered to only include data about 2020, 2021 and 2022
|
| 225 |
"""
|
| 226 |
)
|
|
@@ -441,8 +442,6 @@ def _(mo):
|
|
| 441 |
### Example App
|
| 442 |
|
| 443 |
Let's display the amount of precipitation each station measured within a timeframe, aggregated to a lower granularity.
|
| 444 |
-
|
| 445 |
-
First we'll filter by day
|
| 446 |
"""
|
| 447 |
)
|
| 448 |
return
|
|
@@ -481,7 +480,9 @@ def _(filters, mo, pl, rain, stations, weather):
|
|
| 481 |
mo.stop(filters.value is None)
|
| 482 |
|
| 483 |
_range_seconds = map(lambda hour: hour * 3600, filters.value["hour"])
|
| 484 |
-
_df_seconds = pl.col("datetime").dt.hour() + pl.col("datetime").dt.minute().
|
|
|
|
|
|
|
| 485 |
|
| 486 |
animation_data = (
|
| 487 |
weather.lazy()
|
|
@@ -535,7 +536,7 @@ def _(animation_data, pl, px):
|
|
| 535 |
def _(mo):
|
| 536 |
mo.md(
|
| 537 |
r"""
|
| 538 |
-
If we were missing some rows, we would have circles popping in and out of
|
| 539 |
|
| 540 |
In many scenarios, missing data can also lead to wrong results overall, for example if we were to estimate the total amount of rainfall during the observed period:
|
| 541 |
"""
|
|
@@ -547,7 +548,7 @@ def _(mo):
|
|
| 547 |
def _(dirty_weather, mo, rain, weather):
|
| 548 |
old_estimate = dirty_weather.select(rain.sum()).item()
|
| 549 |
new_estimate = weather.select(rain.sum()).item()
|
| 550 |
-
# Note: The aggregation used to calculate these variables (taking a sum across all stations) is not very meaningful, but the relative
|
| 551 |
|
| 552 |
mo.md(f"Our estimates may change by roughly {(new_estimate - old_estimate) / old_estimate:.2%}")
|
| 553 |
return
|
|
@@ -648,10 +649,6 @@ def _(mo):
|
|
| 648 |
def _(dirty_weather_naive, pl):
|
| 649 |
dirty_weather = dirty_weather_naive.with_columns(pl.col("datetime").dt.replace_time_zone("America/Sao_Paulo"))
|
| 650 |
|
| 651 |
-
# Also get rid of some of the other variables to economize memory
|
| 652 |
-
# del raw_weather
|
| 653 |
-
# del dirty_weather_naive
|
| 654 |
-
|
| 655 |
dirty_weather.head(3)
|
| 656 |
return (dirty_weather,)
|
| 657 |
|
|
@@ -662,9 +659,9 @@ def _(mo):
|
|
| 662 |
r"""
|
| 663 |
## Appendix B: Not a Number
|
| 664 |
|
| 665 |
-
While some other tools without proper support for missing values
|
| 666 |
|
| 667 |
-
You can use `.fill_null(float('nan'))` if you need to convert to a format such tools accept, or use `.fill_nan(None)` if you are importing data from them, assuming that there are no values which really are supposed to be the float NaN.
|
| 668 |
|
| 669 |
Remember that many calculations can result in NaN, for example dividing by zero:
|
| 670 |
"""
|
|
@@ -686,11 +683,14 @@ def _(dirty_weather, pl, rain):
|
|
| 686 |
|
| 687 |
@app.cell(hide_code=True)
|
| 688 |
def _(day_perc, mo, perc_col):
|
| 689 |
-
mo.md(
|
| 690 |
-
|
|
|
|
|
|
|
| 691 |
|
| 692 |
In this case it makes sense to fill in NaNs as 0 to indicate there was no rain during that period, but treating the nulls the same could lead to a different interpretation of the data, so remember to handle NaNs and nulls separately.
|
| 693 |
-
"""
|
|
|
|
| 694 |
return
|
| 695 |
|
| 696 |
|
|
@@ -745,13 +745,15 @@ def _(mo):
|
|
| 745 |
|
| 746 |
@app.cell(hide_code=True)
|
| 747 |
def _(pl):
|
| 748 |
-
age_groups = pl.DataFrame(
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
|
|
|
|
|
|
| 755 |
age_groups
|
| 756 |
return (age_groups,)
|
| 757 |
|
|
@@ -782,8 +784,8 @@ def _(mo):
|
|
| 782 |
|
| 783 |
@app.cell
|
| 784 |
def _(pl):
|
| 785 |
-
raw_stations = pl.read_csv("/
|
| 786 |
-
raw_weather = pl.read_csv("/
|
| 787 |
return raw_stations, raw_weather
|
| 788 |
|
| 789 |
|
|
|
|
| 99 |
return
|
| 100 |
|
| 101 |
|
| 102 |
+
@app.cell(hide_code=True)
|
| 103 |
def _(mo):
|
| 104 |
mo.md(
|
| 105 |
r"""
|
|
|
|
| 108 |
To filter in polars, you'll typically use `df.filter(expression)` or `df.remove(expression)` methods.
|
| 109 |
|
| 110 |
Filter will only keep rows in which the expression evaluates to True.
|
| 111 |
+
It will remove not only rows in which it evaluates to False, but also those in which the expression evaluates to None.
|
| 112 |
|
| 113 |
Remove will only remove rows in which the expression evaluates to True.
|
| 114 |
+
It will keep rows in which it evaluates to None.
|
| 115 |
"""
|
| 116 |
)
|
| 117 |
return
|
|
|
|
| 133 |
def _(mo):
|
| 134 |
mo.md(
|
| 135 |
r"""
|
| 136 |
+
You may also be tempted to use `== None` or `!= None`, but operators in polars will generally propagate null values.
|
| 137 |
|
| 138 |
You can use `.eq_missing()` or `.ne_missing()` methods if you want to be strict about it, but there are also `.is_null()` and `.is_not_null()` methods you can use.
|
| 139 |
"""
|
|
|
|
| 163 |
You can also fill in the values with constants, calculations or by consulting external data sources.
|
| 164 |
|
| 165 |
Be careful not to treat estimated or guessed values as if they a ground truth however, otherwise you may end up making conclusions about a reality that does not exists.
|
| 166 |
+
|
| 167 |
+
As an excercise, let's guess some values to fill in nulls, then try giving names to the animals with `null` by editing the cells
|
| 168 |
"""
|
| 169 |
)
|
| 170 |
return
|
|
|
|
| 179 |
guesstimates = mo.ui.data_editor(
|
| 180 |
guesstimates,
|
| 181 |
editable_columns=["name"],
|
|
|
|
| 182 |
)
|
| 183 |
guesstimates
|
| 184 |
return (guesstimates,)
|
|
|
|
| 202 |
- you could just drop rows with values missing in any columns or a subset of them with `df.drop_nulls()`, but for most cases you'll want to be more careful about it
|
| 203 |
- take into consideration whenever you want to preserve null values or remove them when choosing between `df.filter()` or `df.remove()`
|
| 204 |
- if you don't want to propagate null values, use `_missing` variations of methods such as `eq` vs `eq_missing`
|
| 205 |
+
- you may want to fill in missing values based on calculations via `fill_null`, join and coalesce based on other datasets, or manually edit the data based on external documents
|
| 206 |
|
| 207 |
You can also refer to the polars [User Guide](https://docs.pola.rs/user-guide/expressions/missing-data/) more more information.
|
| 208 |
|
|
|
|
| 221 |
We will be using a dataset from `alertario` about the weather in Rio de Janeiro, originally available in Google Big Query under `datario.clima_pluviometro`. What you need to know about it:
|
| 222 |
|
| 223 |
- Contains multiple stations covering the Municipality of Rio de Janeiro
|
| 224 |
+
- Measures the precipitation as millimeters, with a granularity of 15 minutes
|
| 225 |
- We filtered to only include data about 2020, 2021 and 2022
|
| 226 |
"""
|
| 227 |
)
|
|
|
|
| 442 |
### Example App
|
| 443 |
|
| 444 |
Let's display the amount of precipitation each station measured within a timeframe, aggregated to a lower granularity.
|
|
|
|
|
|
|
| 445 |
"""
|
| 446 |
)
|
| 447 |
return
|
|
|
|
| 480 |
mo.stop(filters.value is None)
|
| 481 |
|
| 482 |
_range_seconds = map(lambda hour: hour * 3600, filters.value["hour"])
|
| 483 |
+
_df_seconds = pl.col("datetime").dt.hour().cast(pl.Float64()).mul(3600) + pl.col("datetime").dt.minute().cast(
|
| 484 |
+
pl.Float64()
|
| 485 |
+
).mul(60)
|
| 486 |
|
| 487 |
animation_data = (
|
| 488 |
weather.lazy()
|
|
|
|
| 536 |
def _(mo):
|
| 537 |
mo.md(
|
| 538 |
r"""
|
| 539 |
+
If we were missing some rows, we would have circles popping in and out of existence instead of a smooth animation!
|
| 540 |
|
| 541 |
In many scenarios, missing data can also lead to wrong results overall, for example if we were to estimate the total amount of rainfall during the observed period:
|
| 542 |
"""
|
|
|
|
| 548 |
def _(dirty_weather, mo, rain, weather):
|
| 549 |
old_estimate = dirty_weather.select(rain.sum()).item()
|
| 550 |
new_estimate = weather.select(rain.sum()).item()
|
| 551 |
+
# Note: The aggregation used to calculate these variables (taking a sum across all stations) is not very meaningful, but the relative difference between them scales across many potentially useful aggregations
|
| 552 |
|
| 553 |
mo.md(f"Our estimates may change by roughly {(new_estimate - old_estimate) / old_estimate:.2%}")
|
| 554 |
return
|
|
|
|
| 649 |
def _(dirty_weather_naive, pl):
|
| 650 |
dirty_weather = dirty_weather_naive.with_columns(pl.col("datetime").dt.replace_time_zone("America/Sao_Paulo"))
|
| 651 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 652 |
dirty_weather.head(3)
|
| 653 |
return (dirty_weather,)
|
| 654 |
|
|
|
|
| 659 |
r"""
|
| 660 |
## Appendix B: Not a Number
|
| 661 |
|
| 662 |
+
While some other tools without proper support for missing values may use `NaN` as a way to indicate a value is missing, in polars it is treated exclusively as a float value, much like `0.0`, `1.0` or `infinity`.
|
| 663 |
|
| 664 |
+
You can use `.fill_null(float('nan'))` if you need to convert floats to a format such tools accept, or use `.fill_nan(None)` if you are importing data from them, assuming that there are no values which really are supposed to be the float NaN.
|
| 665 |
|
| 666 |
Remember that many calculations can result in NaN, for example dividing by zero:
|
| 667 |
"""
|
|
|
|
| 683 |
|
| 684 |
@app.cell(hide_code=True)
|
| 685 |
def _(day_perc, mo, perc_col):
|
| 686 |
+
mo.md(
|
| 687 |
+
f"""
|
| 688 |
+
It is null for {day_perc.select(perc_col.is_null().mean()).item():.4%} of the rows, but is NaN for {day_perc.select(perc_col.is_nan().mean()).item():.4%} of them.
|
| 689 |
+
If we use the cleaned weather dataframe to calculate it instead of the dirty_weather, we will have no nulls, but note how for this calculation we can end up with both, with each having a different meaning.
|
| 690 |
|
| 691 |
In this case it makes sense to fill in NaNs as 0 to indicate there was no rain during that period, but treating the nulls the same could lead to a different interpretation of the data, so remember to handle NaNs and nulls separately.
|
| 692 |
+
"""
|
| 693 |
+
)
|
| 694 |
return
|
| 695 |
|
| 696 |
|
|
|
|
| 745 |
|
| 746 |
@app.cell(hide_code=True)
|
| 747 |
def _(pl):
|
| 748 |
+
age_groups = pl.DataFrame(
|
| 749 |
+
[
|
| 750 |
+
{"age": None, "stage": "Unknown"},
|
| 751 |
+
{"age": [0, 1], "stage": "Baby"},
|
| 752 |
+
{"age": [2, 3, 4, 5, 6, 7, 8, 9, 10], "stage": "Adult"},
|
| 753 |
+
{"age": [11, 12, 13, 14], "stage": "Senior"},
|
| 754 |
+
{"age": [15, 16, 17, 18, 19, 20], "stage": "Geriatric"},
|
| 755 |
+
]
|
| 756 |
+
)
|
| 757 |
age_groups
|
| 758 |
return (age_groups,)
|
| 759 |
|
|
|
|
| 784 |
|
| 785 |
@app.cell
|
| 786 |
def _(pl):
|
| 787 |
+
raw_stations = pl.read_csv("hf://datasets/etrotta/weather-alertario/datario_alertario_stations.csv")
|
| 788 |
+
raw_weather = pl.read_csv("hf://datasets/etrotta/weather-alertario/datario_alertario_weather_2020_to_2022.csv")
|
| 789 |
return raw_stations, raw_weather
|
| 790 |
|
| 791 |
|