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
47 changes: 47 additions & 0 deletions pandas-dataframe/README.md
Original file line number Diff line number Diff line change
@@ -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.
39 changes: 39 additions & 0 deletions pandas-dataframe/accessing_and_modifying_data.py
Original file line number Diff line number Diff line change
@@ -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"])
27 changes: 27 additions & 0 deletions pandas-dataframe/arithmetic_and_numpy.py
Original file line number Diff line number Diff line change
@@ -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)
47 changes: 47 additions & 0 deletions pandas-dataframe/candidates.py
Original file line number Diff line number Diff line change
@@ -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
36 changes: 36 additions & 0 deletions pandas-dataframe/creating_dataframe.py
Original file line number Diff line number Diff line change
@@ -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))
40 changes: 40 additions & 0 deletions pandas-dataframe/inserting_and_deleting_data.py
Original file line number Diff line number Diff line change
@@ -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)
18 changes: 18 additions & 0 deletions pandas-dataframe/introducing_dataframe.py
Original file line number Diff line number Diff line change
@@ -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])
14 changes: 14 additions & 0 deletions pandas-dataframe/iterating.py
Original file line number Diff line number Diff line change
@@ -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)
20 changes: 20 additions & 0 deletions pandas-dataframe/missing_data.py
Original file line number Diff line number Diff line change
@@ -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())
16 changes: 16 additions & 0 deletions pandas-dataframe/plotting.py
Original file line number Diff line number Diff line change
@@ -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()
12 changes: 12 additions & 0 deletions pandas-dataframe/requirements.txt
Original file line number Diff line number Diff line change
@@ -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
31 changes: 31 additions & 0 deletions pandas-dataframe/retrieving_labels_and_data.py
Original file line number Diff line number Diff line change
@@ -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())
18 changes: 18 additions & 0 deletions pandas-dataframe/sorting_and_filtering.py
Original file line number Diff line number Diff line change
@@ -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))
13 changes: 13 additions & 0 deletions pandas-dataframe/statistics.py
Original file line number Diff line number Diff line change
@@ -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()))
Loading
Loading