From the free course pandas documentation on Lykke
Introduction to pandas
Key concepts: Installation (conda/pip) · Virtual Environments · Primary Data Structures (Series & DataFrame) · Core Features for Data Manipulation · Data Representation
This section introduces the pandas library, covering its purpose, core data structures (DataFrame and Series), and installation. It provides the foundational knowledge needed to understand why and how pandas is used for data analysis in Python.
Introduction to pandas
Pandas is an open-source Python library that has become the de facto standard for data manipulation and analysis in the scientific Python ecosystem. Its name is derived from "panel data," an econometrics term for multidimensional structured data sets. Built on top of the NumPy library, pandas provides high-performance, easy-to-use data structures and data analysis tools designed to make working with labeled and relational data both intuitive and efficient. It excels at handling tabular data, heterogeneous columns, and time-series data, bridging the gap between raw data and sophisticated analysis or machine learning models.
At its core, pandas solves a fundamental problem: how to represent and interact with structured data within Python in a way that is both computationally efficient and semantically expressive. Before pandas, data analysts often juggled lists of lists, dictionaries of dictionaries, or NumPy arrays, all of which had significant limitations for the common tasks of cleaning, transforming, filtering, and aggregating real-world datasets. Pandas introduces two primary data structures, the DataFrame and the Series, which provide an integrated, index-aware framework for these tasks, fundamentally changing the landscape of data science in Python.
AI_SVGI_SVG## Installation and Environment Management
Before diving into the library's features, a robust and isolated development environment is paramount. This prevents conflicts between project dependencies and ensures reproducibility. The two most common package managers in the Python data ecosystem are conda and pip.
What it is
Installation is the process of adding the pandas library and its dependencies to your Python environment. A virtual environment is an isolated directory tree that contains a specific Python installation and any additional packages. Working within a virtual environment is a critical best practice.
Why it matters
Data science projects often rely on a complex web of libraries (e.g., pandas, numpy, scikit-learn, matplotlib, tensorflow), each with its own version requirements. Installing everything into the global Python installation can lead to a "dependency hell," where upgrading one package breaks another. Virtual environments solve this by creating a self-contained sandbox for each project. This ensures that your project's dependencies are explicit, consistent across different machines, and do not interfere with other projects.
How it works
Both conda and pip manage package installation, but they operate at different levels. pip is the standard package installer for Python and manages Python packages only. conda is a cross-platform, language-agnostic package and environment manager. It can manage Python packages but also Python itself, as well as non-Python libraries (e.g., C/C++ libraries like MKL or CUDA) that are often dependencies for high-performance scientific packages.
| Feature | conda (via Anaconda/Miniconda) |
pip (with venv) |
|---|---|---|
| Scope | Language-agnostic (Python, R, C++, etc.) | Python-specific |
| Environment Mgmt | Built-in (conda create, conda activate) |
Separate module (venv) |
| Package Source | Anaconda repositories (curated, pre-compiled) | Python Package Index (PyPI) |
| Dependency Resolution | Advanced solver, checks for compatibility across all packages (Python and non-Python) | Can be less robust, especially with complex binary dependencies; newer versions have improved. |
| Typical Use Case | Scientific computing, data science, ML (where binary dependencies are common) | General Python development, web development |
Concrete Example: Setting up an Environment
Here is a typical workflow for creating and activating a virtual environment and installing pandas using conda. This is the recommended approach for most data science applications.
# 1. Create a new conda environment named 'data-analysis' with Python 3.11
# Conda will resolve and install Python and other base packages.
conda create --name data-analysis python=3.11
# 2. Activate the newly created environment.
# Your shell prompt will change to indicate you are in the environment.
conda activate data-analysis
# 3. Install pandas, numpy, and matplotlib from the conda-forge channel.
# conda-forge is a community-led channel with a vast collection of packages.
# Specifying versions ensures reproducibility.
conda install -c conda-forge pandas==2.2.1 numpy==1.26.4 matplotlib==3.8.3
# 4. Verify the installation by checking the pandas version.
python -c "import pandas as pd; print(pd.__version__)"
# 5. When finished, deactivate the environment to return to the base shell.
conda deactivate
This sequence of commands provides a clean, reproducible, and high-performance environment for any data analysis project. Using a requirements file (environment.yml for conda or requirements.txt for pip) is the next step for professional project management.
Primary Data Structures: Series and DataFrame
Pandas represents data in two fundamental structures: the Series and the DataFrame. Mastering these two objects is the key to unlocking the full power of the library. They are not merely containers for data; they are sophisticated objects with a rich API for transformation and analysis.
The Series
A Series is a one-dimensional, array-like object containing a sequence of values of a single data type, and an associated array of data labels, called its index.
What it is
Think of a Series as a smart, labeled array. It is composed of two primary components:
- Data: A sequence of values, typically a NumPy
ndarrayunder the hood. This allows for highly efficient, vectorized operations. - Index: An object (of type
pd.Index) that provides labels for the data. These labels can be integers, strings, dates, or other hashable types. The index allows for fast lookups and alignment of data.
A Series can also have a name attribute, which is useful for identifying it, especially when it's a column in a DataFrame.
How it works
Let's demystify the Series by building a simplified version from scratch. This illustrates the core concept of coupling a data array with an index for labeled access.
import numpy as np
class SimpleSeries:
"""A simplified implementation of a pandas-like Series."""
def __init__(self, data, index=None, name=None):
if not isinstance(data, (list, np.ndarray)):
raise TypeError("Data must be a list or NumPy array.")
self._data = np.asarray(data)
self.name = name
if index is None:
# Default to a range index if none is provided
self._index = np.arange(len(self._data))
else:
if len(data) != len(index):
raise ValueError("Length of data and index must be the same.")
self._index = np.asarray(index)
# Create a mapping from index label to integer position for fast lookups
self._index_map = {label: pos for pos, label in enumerate(self._index)}
def __len__(self):
return len(self._data)
def __repr__(self):
output = ""
for i, val in zip(self._index, self._data):
output += f"{str(i):<10} {str(val)}\n"
dtype_str = f"dtype: {self._data.dtype}"
name_str = f"Name: {self.name}, " if self.name else ""
return f"{output}\n{name_str}Length: {len(self)}, {dtype_str}"
def __getitem__(self, key):
# Support both positional and label-based access
if isinstance(key, int):
return self._data[key]
elif key in self._index_map:
pos = self._index_map[key]
return self._data[pos]
else:
raise KeyError(f"Label not found in index: {key}")
@property
def values(self):
return self._data
@property
def index(self):
return self._index
# Example Usage
population_data = SimpleSeries(
[38_250_000, 39_510_000, 29_140_000],
index=['Canada', 'California', 'Texas'],
name='Population'
)
print(population_data)
print(f"\nPopulation of California: {population_data['California']}")
This simple class captures the essence of a pandas Series: it binds data (_data) to an index (_index) and provides a lookup mechanism (__getitem__) that can work with labels. The real pandas Series is, of course, vastly more complex, with hundreds of optimized methods, robust data type handling, and seamless integration with the rest of the library.
The DataFrame
A DataFrame is a two-dimensional, size-mutable, and potentially heterogeneous tabular data structure with labeled axes (rows and columns).
What it is
A DataFrame is the primary workhorse of pandas. It is best conceptualized in several ways:
- As a spreadsheet or SQL table in memory.
- As a dictionary of Series objects, where the keys are the column names and the values are the Series themselves, all sharing a common index.
It has both a row index and a column index, making it a powerful tool for selecting, aligning, and manipulating data. Each column can have a different data type (e.g., numbers, strings, dates, booleans), which makes it heterogeneous.
Concrete Example: Creating and Inspecting a DataFrame
Let's create a DataFrame from scratch and use some fundamental inspection methods. We'll use the Titanic dataset for this and subsequent examples.
import pandas as pd
import numpy as np
# Load data from a URL
# Using specific dtypes during read can save memory and prevent errors
titanic_df = pd.read_csv(
"https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv",
usecols=['Survived', 'Pclass', 'Name', 'Sex', 'Age', 'Fare'],
dtype={'Pclass': 'category', 'Survived': 'int8'}
)
# Inspect the first few rows
print("--- First 5 rows (head) ---")
print(titanic_df.head())
# Get a concise summary of the DataFrame
# This is invaluable for initial data exploration
print("\n--- Technical Summary (info) ---")
titanic_df.info()
# Generate descriptive statistics for numerical columns
print("\n--- Descriptive Statistics (describe) ---")
print(titanic_df.describe())
The output of .info() is particularly revealing. It shows the row index type and count (RangeIndex: 891 entries), the total number of columns, and for each column: its name, the count of non-null values, and its data type (Dtype). This single command provides a comprehensive overview of the DataFrame's structure and potential data quality issues (like missing values in the Age column).
Series vs. DataFrame
| Aspect | pd.Series |
pd.DataFrame |
|---|---|---|
| Dimensions | 1-D | 2-D |
| Data Structure | Homogeneous labeled array | Heterogeneous labeled table |
| Analogy | A single column in a spreadsheet | An entire spreadsheet or SQL table |
| Components | Data, Index, Name, Dtype | Data, Index (rows), Columns |
| Creation | pd.Series(data, index=...) |
pd.DataFrame(data, index=..., columns=...) |
| Relationship | A column of a DataFrame is a Series. | A collection of Series sharing a common index. |
Core Features for Data Manipulation
A DataFrame is not just a static data container; it is an object with a rich set of methods for transformation and analysis. The power of pandas lies in its ability to perform these operations efficiently and expressively.
Data Ingestion and Representation
Pandas provides a suite of read_* functions for ingesting data from various formats, with pd.read_csv being the most common. These functions are highly optimized and offer dozens of parameters to handle real-world messy data.
Once loaded, the data is represented in memory using a block-based architecture. Columns of the same data type are often grouped together in NumPy arrays, a structure known as the BlockManager. This internal architecture is key to pandas' performance, as it allows NumPy's fast, vectorized C-level operations to be applied to entire blocks of data at once.
Key Insight: Pandas operations are vectorized. This means that operations are applied to entire arrays (Series or columns) at once, rather than iterating over elements one by one in Python. This delegation to underlying, compiled C or Cython code is the primary source of pandas' speed. Avoid writing explicit
forloops over DataFrame rows whenever possible.
Selection and Subsetting (.loc, .iloc)
One of the most common tasks is selecting subsets of data. Pandas provides a powerful and precise syntax for this, which can be a point of confusion for beginners.
| Method | Selection By | Input Type | Behavior | Common Use Case |
|---|---|---|---|---|
df[...] |
Column(s) or Rows | String, list of strings, or boolean array | Ambiguous: selects columns by name, but can slice rows with df[0:5] or filter rows with a boolean mask. |
Quick, interactive column selection (df['Age']) or boolean filtering (df[df['Age'] > 30]). |
df.loc[...] |
Labels | Row labels, column labels | Explicitly label-based. Slices are inclusive of the endpoint. | Selecting data by meaningful index labels (e.g., dates, names) or boolean conditions. |
df.iloc[...] |
Integer Position | Row integers, column integers | Explicitly position-based. Slices are exclusive of the endpoint, like standard Python. | Selecting data by its numerical position, regardless of index labels. |
Common Pitfall: Chained Indexing
A frequent mistake is using chained indexing for assignment, like df[df['Age'] > 60]['Survived'] = 0. This can lead to a SettingWithCopyWarning and unpredictable results because the first indexing operation (df[df['Age'] > 60]) might return a copy of the data, not a view. The subsequent assignment then modifies this temporary copy, which is immediately discarded, leaving the original DataFrame unchanged.
The correct, idiomatic way to perform this assignment is with a single .loc call:
# Create a copy to avoid modifying the original df in later examples
titanic_subset = titanic_df.copy()
# --- INCORRECT: Chained assignment ---
# This may or may not work and raises a warning.
# titanic_subset[titanic_subset['Age'] > 65]['Fare'] = 0
# --- CORRECT: Using .loc for assignment ---
# Select rows based on a boolean condition and columns by label, then assign.
titanic_subset.loc[titanic_subset['Age'] > 65, 'Fare'] = 0
print("Fare for passengers over 65 set to 0:")
print(titanic_subset[titanic_subset['Age'] > 65].head())
The Split-Apply-Combine Strategy
Many complex data analysis problems can be framed using the split-apply-combine paradigm, a concept popularized by Hadley Wickham. Pandas' groupby() operation is the canonical implementation of this pattern.
- Split: The data is split into groups based on some criteria (e.g., by
SexandPclass). - Apply: A function is applied independently to each group (e.g., calculate the mean
Ageor the survival rate). - Combine: The results of the function applications are combined into a new data structure.
Concrete Example: Groupby Aggregation
Let's calculate the average age and survival rate for passengers, grouped by their class and sex.
# Group by passenger class and sex
grouped = titanic_df.groupby(['Pclass', 'Sex'])
# Apply multiple aggregation functions at once using a dictionary
# This is highly efficient and expressive.
agg_results = grouped.agg(
mean_age=('Age', 'mean'),
median_fare=('Fare', 'median'),
survival_rate=('Survived', 'mean'),
count=('Survived', 'count')
)
# The result is a DataFrame with a MultiIndex
print(agg_results.round(2))
This single, expressive command replaces what would be a complex series of loops and conditional logic in traditional programming. It clearly demonstrates the power of the split-apply-combine pattern for summarizing data.
This introduction has covered the foundational concepts of pandas: its purpose, proper setup, the core Series and DataFrame structures, and an overview of its main features. With this foundation, you are equipped to explore the vast capabilities of the library for cleaning, transforming, modeling, and visualizing data.
Source Materials
Study pandas documentation on Lykke
This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.
Add the free extensionSign in to open every sectionAll sections of pandas documentation · Browse more course pages