diff --git a/pandas-groupby/README.md b/pandas-groupby/README.md index dbd41aa95a..44799803f9 100644 --- a/pandas-groupby/README.md +++ b/pandas-groupby/README.md @@ -1,3 +1,40 @@ -# Pandas-Groupby +# pandas GroupBy: Your Guide to Grouping Data in Python -Supporting CSV files for the article [All You Need to Know About Pandas' GroupBy](https://realpython.com/pandas-groupby/). +This folder contains the sample code and datasets for the Real Python tutorial [pandas GroupBy: Your Guide to Grouping Data in Python](https://realpython.com/pandas-groupby/). + +- `groupby-data.zip` holds the three datasets: `legislators-historical.csv`, `airqual.csv`, and `news.csv`. +- `pandas_legislators.py` loads the U.S. Congress dataset. +- `pandas_airqual.py` loads the air quality dataset. +- `pandas_news.py` loads the news aggregator dataset. +- `pandas_news_performance.py` compares `.groupby().apply()` with a vectorized version. + +## Setup + +Create and activate a virtual environment, then install the pinned dependencies: + +```console +$ python -m venv venv/ +$ source venv/bin/activate +(venv) $ python -m pip install -r requirements.txt +``` + +Unzip `groupby-data.zip` into a folder called `groupby-data/` next to the scripts: + +```console +(venv) $ unzip groupby-data.zip -x "__MACOSX/*" -d groupby-data/ +``` + +## Usage + +Import a dataset's `DataFrame` in the Python REPL: + +```pycon +>>> from pandas_legislators import df +>>> df.tail() +``` + +Run the performance comparison as a script: + +```console +(venv) $ python pandas_news_performance.py +``` diff --git a/pandas-groupby/pandas_airqual.py b/pandas-groupby/pandas_airqual.py new file mode 100644 index 0000000000..557a9f52f9 --- /dev/null +++ b/pandas-groupby/pandas_airqual.py @@ -0,0 +1,18 @@ +import pandas as pd + +df = pd.read_csv( + "groupby-data/airqual.csv", + na_values=[-200], + usecols=["Date", "Time", "CO(GT)", "T", "RH", "AH"], +) +df["tstamp"] = pd.to_datetime( + df.pop("Date") + " " + df.pop("Time"), format="%m/%d/%y %H:%M:%S" +) +df = df.rename( + columns={ + "CO(GT)": "co", + "T": "temp_c", + "RH": "rel_hum", + "AH": "abs_hum", + } +).set_index("tstamp") diff --git a/pandas-groupby/pandas_legislators.py b/pandas-groupby/pandas_legislators.py new file mode 100644 index 0000000000..db4ecb493e --- /dev/null +++ b/pandas-groupby/pandas_legislators.py @@ -0,0 +1,15 @@ +import pandas as pd + +dtypes = { + "first_name": "category", + "gender": "category", + "type": "category", + "state": "category", + "party": "category", +} +df = pd.read_csv( + "groupby-data/legislators-historical.csv", + dtype=dtypes, + usecols=list(dtypes) + ["birthday", "last_name"], + parse_dates=["birthday"], +) diff --git a/pandas-groupby/pandas_news.py b/pandas-groupby/pandas_news.py new file mode 100644 index 0000000000..829977653b --- /dev/null +++ b/pandas-groupby/pandas_news.py @@ -0,0 +1,16 @@ +import pandas as pd + +df = pd.read_csv( + "groupby-data/news.csv", + sep="\t", + header=None, + index_col=0, + names=["title", "url", "outlet", "category", "cluster", "host", "tstamp"], + dtype={ + "outlet": "category", + "category": "category", + "cluster": "category", + "host": "category", + }, +) +df["tstamp"] = pd.to_datetime(df["tstamp"], unit="ms") diff --git a/pandas-groupby/pandas_news_performance.py b/pandas-groupby/pandas_news_performance.py new file mode 100644 index 0000000000..8556b0a090 --- /dev/null +++ b/pandas-groupby/pandas_news_performance.py @@ -0,0 +1,23 @@ +import timeit +import numpy as np + +from pandas_news import df + + +def test_apply(): + """Version 1: using `.apply()`""" + df.groupby("outlet", sort=False)["title"].apply( + lambda ser: ser.str.contains("Fed").sum() + ).nlargest(10) + + +def test_vectorization(): + """Version 2: using vectorization""" + mentions_fed = df["title"].str.contains("Fed") + mentions_fed.groupby(df["outlet"], sort=False).sum().nlargest(10).astype( + np.uintc + ) + + +print(f"Version 1: {timeit.timeit(test_apply, number=3)}") +print(f"Version 2: {timeit.timeit(test_vectorization, number=3)}") diff --git a/pandas-groupby/requirements.txt b/pandas-groupby/requirements.txt new file mode 100644 index 0000000000..e0fa4048ba --- /dev/null +++ b/pandas-groupby/requirements.txt @@ -0,0 +1,2 @@ +pandas==3.1.1 +numpy==2.5.4