Skip to content
BIASED

Data frames with pandas

Block 1 of 8~3 min

Columns over arrays

The topic NumPy arrays ended with what an array cannot hold. An array has one dtype, and you find an element by its position. Real data come as tables: a column of run names next to a column of losses and a column of dates, rows found by a key, some values missing. The topic Files and exceptions read such a table, metrics.csv, with the csv module and got every field back as a string.

pandas stores a table as a DataFrame. The examples use Python 3.14.7, pandas 3.1.0 and NumPy 2.5.4, without PyArrow, run with uv run --python 3.14 --with "pandas>=3" python. From the second session on, import numpy as np and import pandas as pd are assumed.

>>> import pandas as pd
>>> df = pd.DataFrame({"run": ["a", "b", "c"],
...                    "loss": [0.58, 0.49, 0.80],
...                    "epochs": [3, 3, 2]})
>>> df
  run  loss  epochs
0   a  0.58       3
1   b  0.49       3
2   c  0.80       2
>>> df.dtypes
run           str
loss      float64
epochs      int64
dtype: object
>>> df.index
RangeIndex(start=0, stop=3, step=1)
>>> type(df["loss"]).__name__, df["loss"].to_numpy()
('Series', array([0.58, 0.49, 0.8 ]))

Key idea. A Series is a one-dimensional array of values plus an Index of labels, one label per value. A DataFrame is a set of named columns that share one row Index. Each column is a Series with its own dtype, stored as a NumPy array or a pandas array of its own.

Here loss is a NumPy float64 array, epochs is int64, and run has the dtype str, the default for text since pandas 3.0. With no index given, pandas numbers the rows 0, 1, 2. That RangeIndex stores only its start, stop and step, so it costs no memory. df["loss"] is one column, a Series, and .to_numpy() returns the array underneath.

Why columns. Analysis works column by column, so pandas stores a table that way. df["loss"].mean() is one NumPy reduction over one array. Reading one row is the expensive direction: it must collect a value from every column and, with mixed dtypes, wrap them into Python objects. This decides which pandas code is fast, as the block on row loops measures.

Alignment. Arithmetic between two Series matches values by label, not by position. A label present in only one of them gives NaN, the floating-point "not a number" that pandas uses for a missing value:

>>> s = pd.Series([0.92, 0.85, 0.95], index=["a", "b", "c"])
>>> u = pd.Series([0.58, 0.49], index=["b", "a"])
>>> s - u
a    0.43
b    0.27
c     NaN
dtype: float64

u lists b before a, and the subtraction still pairs a with a: 0.92−0.49=0.430.92 - 0.49 = 0.43. Label c has no partner, so its result is missing.

Answers are saved on the server and tied to this browser until you sign in.