Series, DataFrames, and indexes

3.1.1

Understand the objects pandas uses for labeled tabular data and how they align values.

On this page

Series and DataFrame

A Series is one-dimensional and has an index. A DataFrame is a two-dimensional table whose columns can have different dtypes. Selecting one column by a scalar label generally gives a Series. Selecting a list of columns gives a DataFrame.

import pandas as pd

frame = pd.DataFrame({"item": ["Coffee", "Tea"], "price": [2.0, 1.5]})
print(frame.shape)
print(frame["price"].tolist())
A DataFrame has item and price columns. Selecting price gives a Series with values 2.0 and 1.5 and the same index labels. Download image
A single column selection keeps the row index.
Example output
(2, 2)
[2.0, 1.5]

Index alignment

Arithmetic between Series aligns by label. If only one Series contains a label, the usual sum is missing at that label. Use add(fill_value=0) only when a missing side should count as zero.

import pandas as pd

morning = pd.Series({"Tea": 2, "Coffee": 4})
evening = pd.Series({"Coffee": 3, "Cake": 1})
print(morning.add(evening, fill_value=0).sort_index().to_dict())
Example output
{'Cake': 1.0, 'Coffee': 7.0, 'Tea': 2.0}

Official references