Skip to content
Open
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
39 changes: 39 additions & 0 deletions python-pandas-tricks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Python pandas: Tricks & Features You May Not Know

This folder contains the sample code for the Real Python tutorial [Python pandas: Tricks & Features You May Not Know](https://realpython.com/python-pandas-tricks/).

- `pandas_startup.py` configures pandas display options at interpreter startup (trick #1).
- `membership_map.py` bins the values of a Series by group membership with `Series.map()` (trick #7).

## Setup

You need Python 3.11 or later. 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
```

## Usage

Point `PYTHONSTARTUP` at the startup script to launch an interpreter session with pandas imported and your display options set:

```console
(venv) $ PYTHONSTARTUP=pandas_startup.py python
>>> pd.get_option("display.max_rows")
14
```

Run the membership mapping example as a script:

```console
(venv) $ python membership_map.py
0 North America
1 North America
2 North America
3 Europe
4 Europe
5 other
dtype: str
```
31 changes: 31 additions & 0 deletions python-pandas-tricks/membership_map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Bin the values of a Series by group membership with Series.map()."""

from typing import Any

import pandas as pd


def membership_map(
s: pd.Series, groups: dict, fillvalue: Any = -1
) -> pd.Series:
# Reverse & expand the dictionary key-value pairs
groups = {x: k for k, v in groups.items() for x in v}
return s.map(groups).fillna(fillvalue)


if __name__ == "__main__":
countries = pd.Series(
[
"United States",
"Canada",
"Mexico",
"Belgium",
"United Kingdom",
"Thailand",
]
)
groups = {
"North America": ("United States", "Canada", "Mexico", "Greenland"),
"Europe": ("France", "Germany", "United Kingdom", "Belgium"),
}
print(membership_map(countries, groups, fillvalue="other"))
31 changes: 31 additions & 0 deletions python-pandas-tricks/pandas_startup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Configure pandas display options at interpreter startup.

Point the PYTHONSTARTUP environment variable at this file, and every
interactive session starts with pandas imported and these options set.
"""

import pandas as pd


def start():
options = {
"display": {
"max_columns": None,
"max_colwidth": 25,
"expand_frame_repr": False, # Don't wrap to multiple pages
"max_rows": 14,
"min_rows": 14,
"max_seq_items": 50, # Max length of printed sequence
"precision": 4,
"show_dimensions": False,
},
}

for category, option in options.items():
for op, value in option.items():
pd.set_option(f"{category}.{op}", value)


if __name__ == "__main__":
start()
del start # Clean up namespace in the interpreter
2 changes: 2 additions & 0 deletions python-pandas-tricks/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pandas==3.1.2
numpy==2.5.5
Loading