From e43cd07e7306b734dfccc9ae0c6caa3c61c2e1d3 Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:45:41 +0000 Subject: [PATCH] Add pandas-dataframe materials folder Companion code for The pandas DataFrame: Make Working With Data Delightful, mirroring the pandas 3.1 update draft. Co-Authored-By: Claude Opus 5.5 --- pandas-dataframe/README.md | 47 +++++++++++++++++++ .../accessing_and_modifying_data.py | 39 +++++++++++++++ pandas-dataframe/arithmetic_and_numpy.py | 27 +++++++++++ pandas-dataframe/candidates.py | 47 +++++++++++++++++++ pandas-dataframe/creating_dataframe.py | 36 ++++++++++++++ .../inserting_and_deleting_data.py | 40 ++++++++++++++++ pandas-dataframe/introducing_dataframe.py | 18 +++++++ pandas-dataframe/iterating.py | 14 ++++++ pandas-dataframe/missing_data.py | 20 ++++++++ pandas-dataframe/plotting.py | 16 +++++++ pandas-dataframe/requirements.txt | 12 +++++ .../retrieving_labels_and_data.py | 31 ++++++++++++ pandas-dataframe/sorting_and_filtering.py | 18 +++++++ pandas-dataframe/statistics.py | 13 +++++ pandas-dataframe/temperatures.py | 38 +++++++++++++++ pandas-dataframe/time_series.py | 18 +++++++ 16 files changed, 434 insertions(+) create mode 100644 pandas-dataframe/README.md create mode 100644 pandas-dataframe/accessing_and_modifying_data.py create mode 100644 pandas-dataframe/arithmetic_and_numpy.py create mode 100644 pandas-dataframe/candidates.py create mode 100644 pandas-dataframe/creating_dataframe.py create mode 100644 pandas-dataframe/inserting_and_deleting_data.py create mode 100644 pandas-dataframe/introducing_dataframe.py create mode 100644 pandas-dataframe/iterating.py create mode 100644 pandas-dataframe/missing_data.py create mode 100644 pandas-dataframe/plotting.py create mode 100644 pandas-dataframe/requirements.txt create mode 100644 pandas-dataframe/retrieving_labels_and_data.py create mode 100644 pandas-dataframe/sorting_and_filtering.py create mode 100644 pandas-dataframe/statistics.py create mode 100644 pandas-dataframe/temperatures.py create mode 100644 pandas-dataframe/time_series.py diff --git a/pandas-dataframe/README.md b/pandas-dataframe/README.md new file mode 100644 index 0000000000..c16d7af1e4 --- /dev/null +++ b/pandas-dataframe/README.md @@ -0,0 +1,47 @@ +# The pandas DataFrame: Make Working With Data Delightful + +This folder provides the code examples for the Real Python tutorial [The pandas DataFrame: Make Working With Data Delightful](https://realpython.com/pandas-dataframe/). + +## Setup + +You'll need Python 3.12 or later. Consider creating a [Python virtual environment](https://realpython.com/python-virtual-environments-a-primer/) before installing the dependencies: + +```console +$ python3 -m venv .venv/ --prompt pandas-dataframe +$ source .venv/bin/activate +(pandas-dataframe) $ python -m pip install -r requirements.txt +``` + +## Usage + +Run the scripts from inside this folder, since they import the shared example data from `candidates.py` and `temperatures.py`: + +```console +(pandas-dataframe) $ python introducing_dataframe.py +``` + +Each script holds the code from one part of the tutorial. The examples that the tutorial shows at the interactive prompt are `print()` calls here, in the same order as the article: + +| File | Tutorial section | +| --- | --- | +| `introducing_dataframe.py` | Introducing the pandas DataFrame | +| `creating_dataframe.py` | Creating a pandas DataFrame | +| `retrieving_labels_and_data.py` | Retrieving Labels and Data | +| `accessing_and_modifying_data.py` | Accessing and Modifying Data | +| `inserting_and_deleting_data.py` | Inserting and Deleting Data | +| `arithmetic_and_numpy.py` | Applying Arithmetic Operations, Applying NumPy and SciPy Functions | +| `sorting_and_filtering.py` | Sorting a pandas DataFrame, Filtering Data | +| `statistics.py` | Determining Data Statistics | +| `missing_data.py` | Handling Missing Data | +| `iterating.py` | Iterating Over a pandas DataFrame | +| `time_series.py` | Working With Time Series | +| `plotting.py` | Plotting With pandas DataFrames | + +Two modules hold the example data shared between the scripts: + +| File | Description | +| --- | --- | +| `candidates.py` | The job candidates' names, cities, ages, and test scores, plus helpers that rebuild the DataFrame at the point where a section starts. | +| `temperatures.py` | Hourly temperatures for one day, used by the time-series and plotting examples. | + +Running `creating_dataframe.py` writes `data.csv`, and running `plotting.py` writes `temperatures.png` to this folder. The plotting script opens Matplotlib windows with `plt.show()`, so close each window to continue. diff --git a/pandas-dataframe/accessing_and_modifying_data.py b/pandas-dataframe/accessing_and_modifying_data.py new file mode 100644 index 0000000000..669ffaff05 --- /dev/null +++ b/pandas-dataframe/accessing_and_modifying_data.py @@ -0,0 +1,39 @@ +"""Getting and setting data with [], .loc[], .iloc[], .at[], and .iat[].""" + +import numpy as np +import pandas as pd + +from candidates import create_candidates + +df = create_candidates() +df.index = np.arange(10, 17) + +print(df["name"]) +print(df.loc[10]) + +# Getting data with accessors +print(df.loc[10]) +print(df.iloc[0]) + +print(df.loc[:, "city"]) +print(df.iloc[:, 1]) + +print(df.loc[11:15, ["name", "city"]]) +print(df.iloc[1:6, [0, 1]]) + +print(df.iloc[1:6:2, 0]) +print(df.iloc[slice(1, 6, 2), 0]) +print(df.iloc[np.s_[1:6:2], 0]) +print(df.iloc[pd.IndexSlice[1:6:2], 0]) + +print(repr(df.at[12, "name"])) +print(repr(df.iat[2, 0])) + +# Setting data with accessors +print(df.loc[:, "py-score"]) +df.loc[:13, "py-score"] = [40, 50, 60, 70] +df.loc[14:, "py-score"] = 0 +print(df["py-score"]) + +df.iloc[:, -1] = np.array([88.0, 79.0, 81.0, 80.0, 68.0, 61.0, 84.0]) +print(df["py-score"]) diff --git a/pandas-dataframe/arithmetic_and_numpy.py b/pandas-dataframe/arithmetic_and_numpy.py new file mode 100644 index 0000000000..73ac3ba81e --- /dev/null +++ b/pandas-dataframe/arithmetic_and_numpy.py @@ -0,0 +1,27 @@ +"""Applying arithmetic operations and NumPy functions to a DataFrame.""" + +import numpy as np + +from candidates import create_scores + +df = create_scores(with_total=False) + +# Arithmetic operations +print(df["py-score"] + df["js-score"]) +print(df["py-score"] / 100) + +df["total"] = ( + 0.4 * df["py-score"] + 0.3 * df["django-score"] + 0.3 * df["js-score"] +) +print(df) + +# NumPy functions +score = df.iloc[:, 2:5] +print(score) +print(repr(np.average(score, axis=1, weights=[0.4, 0.3, 0.3]))) + +del df["total"] +print(df) + +df["total"] = np.average(df.iloc[:, 2:5], axis=1, weights=[0.4, 0.3, 0.3]) +print(df) diff --git a/pandas-dataframe/candidates.py b/pandas-dataframe/candidates.py new file mode 100644 index 0000000000..6a32274c3e --- /dev/null +++ b/pandas-dataframe/candidates.py @@ -0,0 +1,47 @@ +"""Shared example data: the job candidates used throughout the tutorial.""" + +import numpy as np +import pandas as pd + +data = { + "name": ["Xavier", "Ann", "Jana", "Yi", "Robin", "Amal", "Nori"], + "city": [ + "Mexico City", + "Toronto", + "Prague", + "Shanghai", + "Manchester", + "Cairo", + "Osaka", + ], + "age": [41, 28, 33, 34, 38, 31, 37], + "py-score": [88.0, 79.0, 81.0, 80.0, 68.0, 61.0, 84.0], +} +row_labels = [101, 102, 103, 104, 105, 106, 107] + + +def create_candidates(): + """Return the DataFrame from the first section of the tutorial.""" + return pd.DataFrame(data=data, index=row_labels) + + +def create_scores(with_total=True): + """Return the DataFrame as it looks after "Inserting and Deleting Data". + + With ``with_total=True``, it also has the weighted ``total`` column from + "Applying NumPy and SciPy Functions". + """ + df = create_candidates() + df.index = np.arange(10, 17) + df["js-score"] = np.array([71.0, 95.0, 88.0, 79.0, 91.0, 91.0, 80.0]) + df.insert( + loc=4, + column="django-score", + value=np.array([86.0, 81.0, 78.0, 88.0, 74.0, 70.0, 81.0]), + ) + df = df.drop(labels="age", axis=1) + if with_total: + df["total"] = np.average( + df.iloc[:, 2:5], axis=1, weights=[0.4, 0.3, 0.3] + ) + return df diff --git a/pandas-dataframe/creating_dataframe.py b/pandas-dataframe/creating_dataframe.py new file mode 100644 index 0000000000..ce764204ab --- /dev/null +++ b/pandas-dataframe/creating_dataframe.py @@ -0,0 +1,36 @@ +"""Creating a pandas DataFrame from dictionaries, lists, arrays, and files.""" + +import numpy as np +import pandas as pd + +from candidates import create_candidates + +# With dictionaries +d = {"x": [1, 2, 3], "y": np.array([2, 4, 8]), "z": 100} +print(pd.DataFrame(d)) +print(pd.DataFrame(d, index=[100, 200, 300], columns=["z", "y", "x"])) + +# With lists +l = [ # noqa: E741 + {"x": 1, "y": 2, "z": 100}, + {"x": 2, "y": 4, "z": 100}, + {"x": 3, "y": 8, "z": 100}, +] +print(pd.DataFrame(l)) + +l = [[1, 2, 100], [2, 4, 100], [3, 8, 100]] # noqa: E741 +print(pd.DataFrame(l, columns=["x", "y", "z"])) + +# With NumPy arrays +arr = np.array([[1, 2, 100], [2, 4, 100], [3, 8, 100]]) +df_ = pd.DataFrame(arr, columns=["x", "y", "z"]) +print(df_) + +df_ = pd.DataFrame(arr, columns=["x", "y", "z"], copy=False) +arr[0, 0] = 1000 +print(df_) + +# From files +df = create_candidates() +df.to_csv("data.csv") +print(pd.read_csv("data.csv", index_col=0)) diff --git a/pandas-dataframe/inserting_and_deleting_data.py b/pandas-dataframe/inserting_and_deleting_data.py new file mode 100644 index 0000000000..9572481af2 --- /dev/null +++ b/pandas-dataframe/inserting_and_deleting_data.py @@ -0,0 +1,40 @@ +"""Inserting and deleting rows and columns.""" + +import numpy as np +import pandas as pd + +from candidates import create_candidates + +df = create_candidates() +df.index = np.arange(10, 17) + +# Rows +john = pd.Series(data=["John", "Boston", 34, 79], index=df.columns, name=17) +print(john) +print(john.name) + +df = pd.concat([df, pd.DataFrame([john])]) +print(df) + +df = df.drop(labels=[17]) +print(df) + +# Columns +df["js-score"] = np.array([71.0, 95.0, 88.0, 79.0, 91.0, 91.0, 80.0]) +print(df) + +df["total-score"] = 0.0 +print(df) + +df.insert( + loc=4, + column="django-score", + value=np.array([86.0, 81.0, 78.0, 88.0, 74.0, 70.0, 81.0]), +) +print(df) + +del df["total-score"] +print(df) + +df = df.drop(labels="age", axis=1) +print(df) diff --git a/pandas-dataframe/introducing_dataframe.py b/pandas-dataframe/introducing_dataframe.py new file mode 100644 index 0000000000..4ca632c7b5 --- /dev/null +++ b/pandas-dataframe/introducing_dataframe.py @@ -0,0 +1,18 @@ +"""Introducing the pandas DataFrame.""" + +import pandas as pd + +from candidates import data, row_labels + +df = pd.DataFrame(data=data, index=row_labels) +print(df) + +print(df.head(n=2)) +print(df.tail(n=2)) + +cities = df["city"] +print(cities) +print(df.city) + +print(repr(cities[102])) +print(df.loc[103]) diff --git a/pandas-dataframe/iterating.py b/pandas-dataframe/iterating.py new file mode 100644 index 0000000000..15968f3904 --- /dev/null +++ b/pandas-dataframe/iterating.py @@ -0,0 +1,14 @@ +"""Iterating over a DataFrame with .items(), .iterrows(), and .itertuples().""" + +from candidates import create_scores + +df = create_scores() + +for col_label, col in df.items(): + print(col_label, col, sep="\n", end="\n\n") + +for row_label, row in df.iterrows(): + print(row_label, row, sep="\n", end="\n\n") + +for row in df.loc[:, ["name", "city", "total"]].itertuples(): + print(row) diff --git a/pandas-dataframe/missing_data.py b/pandas-dataframe/missing_data.py new file mode 100644 index 0000000000..f342dfaae4 --- /dev/null +++ b/pandas-dataframe/missing_data.py @@ -0,0 +1,20 @@ +"""Calculating with, filling, and deleting missing data.""" + +import numpy as np +import pandas as pd + +df_ = pd.DataFrame({"x": [1, 2, np.nan, 4]}) +print(df_) + +# Calculating with missing data +print(df_.mean()) +print(df_.mean(skipna=False)) + +# Filling missing data +print(df_.fillna(value=0)) +print(df_.ffill()) +print(df_.bfill()) +print(df_.interpolate()) + +# Deleting rows and columns with missing data +print(df_.dropna()) diff --git a/pandas-dataframe/plotting.py b/pandas-dataframe/plotting.py new file mode 100644 index 0000000000..822cdb40f5 --- /dev/null +++ b/pandas-dataframe/plotting.py @@ -0,0 +1,16 @@ +"""Plotting with pandas DataFrames and Matplotlib.""" + +import matplotlib.pyplot as plt + +from candidates import create_scores +from temperatures import create_temperatures + +temp = create_temperatures() +temp.plot() +plt.show() + +temp.plot().get_figure().savefig("temperatures.png") + +df = create_scores() +df.loc[:, ["py-score", "total"]].plot.hist(bins=5, alpha=0.4) +plt.show() diff --git a/pandas-dataframe/requirements.txt b/pandas-dataframe/requirements.txt new file mode 100644 index 0000000000..19f32382a3 --- /dev/null +++ b/pandas-dataframe/requirements.txt @@ -0,0 +1,12 @@ +contourpy==1.4.0 +cycler==0.12.1 +fonttools==4.69.1 +kiwisolver==1.5.1 +matplotlib==3.11.2 +numpy==2.5.5 +packaging==26.4 +pandas==3.1.2 +pillow==13.0.0 +pyparsing==3.3.3 +python-dateutil==4.0.0 +tzdata==2026.6 diff --git a/pandas-dataframe/retrieving_labels_and_data.py b/pandas-dataframe/retrieving_labels_and_data.py new file mode 100644 index 0000000000..4614daa92a --- /dev/null +++ b/pandas-dataframe/retrieving_labels_and_data.py @@ -0,0 +1,31 @@ +"""Retrieving labels, data, data types, and size of a DataFrame.""" + +import numpy as np + +from candidates import create_candidates + +df = create_candidates() + +# Labels as sequences +print(df.index) +print(df.columns) +print(repr(df.columns[1])) + +df.index = np.arange(10, 17) +print(df.index) +print(df) + +# Data as NumPy arrays +print(repr(df.to_numpy())) + +# Data types +print(df.dtypes) + +df_ = df.astype(dtype={"age": np.int32, "py-score": np.float32}) +print(df_.dtypes) + +# Size +print(df_.ndim) +print(df_.shape) +print(df_.size) +print(df_.memory_usage()) diff --git a/pandas-dataframe/sorting_and_filtering.py b/pandas-dataframe/sorting_and_filtering.py new file mode 100644 index 0000000000..5c799bf472 --- /dev/null +++ b/pandas-dataframe/sorting_and_filtering.py @@ -0,0 +1,18 @@ +"""Sorting and filtering a DataFrame.""" + +from candidates import create_scores + +df = create_scores() + +# Sorting +print(df.sort_values(by="js-score", ascending=False)) +print(df.sort_values(by=["total", "py-score"], ascending=[False, False])) + +# Filtering +filter_ = df["django-score"] >= 80 +print(filter_) +print(df[filter_]) + +print(df[(df["py-score"] >= 80) & (df["js-score"] >= 80)]) + +print(df["django-score"].where(cond=df["django-score"] >= 80, other=0.0)) diff --git a/pandas-dataframe/statistics.py b/pandas-dataframe/statistics.py new file mode 100644 index 0000000000..a5679891ef --- /dev/null +++ b/pandas-dataframe/statistics.py @@ -0,0 +1,13 @@ +"""Determining data statistics.""" + +from candidates import create_scores + +df = create_scores() + +print(df.describe()) + +print(df.mean(numeric_only=True)) +print(repr(df["py-score"].mean())) + +print(df.std(numeric_only=True)) +print(repr(df["py-score"].std())) diff --git a/pandas-dataframe/temperatures.py b/pandas-dataframe/temperatures.py new file mode 100644 index 0000000000..02a479c0e2 --- /dev/null +++ b/pandas-dataframe/temperatures.py @@ -0,0 +1,38 @@ +"""Shared time-series data: hourly temperatures on October 27, 2019.""" + +import pandas as pd + +temp_c = [ + # fmt: off + 8.0, + 7.1, + 6.8, + 6.4, + 6.0, + 5.4, + 4.8, + 5.0, + 9.1, + 12.8, + 15.3, + 19.1, + 21.2, + 22.1, + 22.4, + 23.1, + 21.0, + 17.9, + 15.5, + 14.4, + 11.9, + 11.0, + 10.2, + 9.1, + # fmt: on +] + + +def create_temperatures(): + """Return the hourly temperature DataFrame with a DatetimeIndex.""" + dt = pd.date_range(start="2019-10-27 00:00:00.0", periods=24, freq="h") + return pd.DataFrame(data={"temp_c": temp_c}, index=dt) diff --git a/pandas-dataframe/time_series.py b/pandas-dataframe/time_series.py new file mode 100644 index 0000000000..1eb86e9ed6 --- /dev/null +++ b/pandas-dataframe/time_series.py @@ -0,0 +1,18 @@ +"""Working with time series: creating, slicing, resampling, and rolling.""" + +import pandas as pd + +from temperatures import temp_c + +dt = pd.date_range(start="2019-10-27 00:00:00.0", periods=24, freq="h") +print(dt) + +temp = pd.DataFrame(data={"temp_c": temp_c}, index=dt) +print(temp) + +# Indexing and slicing +print(temp["2019-10-27 05":"2019-10-27 14"]) + +# Resampling and rolling +print(temp.resample(rule="6h").mean()) +print(temp.rolling(window=3).mean())