Data Wrangling with Python Datatable - Transformations Within a GroupBy#
Link to Source data#
Task: Group data by Date and Zip and get the ratio of Price to maximum Price per group.
from datatable import dt, f, update, by
df = dt.Frame(
{
"Date": ["2019-01-01", "2019-01-01", "2019-01-01", "2019-01-01", "2019-01-01"],
"Zip": [90102, 90102, 90102, 90102, 90103],
"Price": [58.02, 81.55, 11.97, 93.23, 13.68],
}
)
df
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[1], line 1
----> 1 from datatable import dt, f, update, by
2
3 df = dt.Frame(
4 {
File /opt/hostedtoolcache/Python/3.11.17/x64/lib/python3.11/site-packages/datatable/__init__.py:181
178 del datatable
180 # This will run only in Jupyter notebook
--> 181 init_styles()
183 options = dt.options.Config(options={}, prefix="")
184 dt.lib._datatable.initialize_options(options)
AttributeError: module 'IPython.core.display' has no attribute 'display'
SOLUTION
df[:, update(Ratio=f.Price / f.Price.max()), by("Date", "Zip")]
df
| Date | Zip | Price | Ratio | |
|---|---|---|---|---|
| ▪▪▪▪ | ▪▪▪▪ | ▪▪▪▪▪▪▪▪ | ▪▪▪▪▪▪▪▪ | |
| 0 | 2019-01-01 | 90102 | 58.02 | 0.622332 |
| 1 | 2019-01-01 | 90102 | 81.55 | 0.874718 |
| 2 | 2019-01-01 | 90102 | 11.97 | 0.128392 |
| 3 | 2019-01-01 | 90102 | 93.23 | 1 |
| 4 | 2019-01-01 | 90103 | 13.68 | 1 |
Resources:
Comments#