Sub topic 1
pandas Series and DataFrames: Labeled Data, Selection, and Aggregation
Prerequisites
Assume basic Python imports, lists, dictionaries, functions, and running code in a script or notebook. A basic understanding of table rows and columns is helpful.
Series: one-dimensional labeled data
A pandas Series is a one-dimensional array with labels. It contains values, an Index, and a dtype, which describes the values’ data type.
import pandas as pd
scores = pd.Series(
[10, 20, 30],
index=["a", "b", "c"],
name="score",
)
print(scores["b"]) # 20, selected by label
print(scores.iloc[0]) # 10, selected by position
print(scores.index) # Index(['a', 'b', 'c'], dtype='object')
print(scores.dtype) # int64The Index: how pandas identifies rows
The Index gives each value an identity. Label selection uses the label itself, while positional selection uses its integer location. Labels do not need to be consecutive numbers, and they can be strings, dates, or other supported values.
DataFrame: a table of aligned columns
A DataFrame is a two-dimensional table. Each column is a Series, and columns share the same row index. When you construct columns with equal lengths, pandas aligns their values by row position and stores one common index.
cities = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune"],
"population_m": [0.7, 10.7, 3.1],
})
print(cities)
print(cities["city"]) # one Seriesdtypes and converting types
Each Series has a dtype. Pandas chooses dtypes when data is created, but imported or mixed data may need conversion. Use methods such as astype deliberately, because conversion can fail or change missing-value behavior.
cities["population_m"] = cities["population_m"].astype("float64")
print(cities.dtypes)Loading and saving tabular data
Use read_csv to load comma-separated data. Use to_csv to save a DataFrame. index=False prevents pandas from writing the DataFrame index as an extra column.
import pandas as pd
df = pd.read_csv("cities.csv")
df.to_csv("cities_clean.csv", index=False)Exercise
Which expression selects the value with label "b" from a Series named scores?
Show answer
scores["b"]. The expression scores.iloc[1] selects the second position instead.