Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions pandas-groupby/README.md
Original file line number Diff line number Diff line change
@@ -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
```
18 changes: 18 additions & 0 deletions pandas-groupby/pandas_airqual.py
Original file line number Diff line number Diff line change
@@ -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")
15 changes: 15 additions & 0 deletions pandas-groupby/pandas_legislators.py
Original file line number Diff line number Diff line change
@@ -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"],
)
16 changes: 16 additions & 0 deletions pandas-groupby/pandas_news.py
Original file line number Diff line number Diff line change
@@ -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")
23 changes: 23 additions & 0 deletions pandas-groupby/pandas_news_performance.py
Original file line number Diff line number Diff line change
@@ -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)}")
2 changes: 2 additions & 0 deletions pandas-groupby/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pandas==3.1.1
numpy==2.5.4
Loading