1. Home
  2. Explore
  3. Computer Science
  4. Pandas Library Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Pandas Library Fundamentals

Pandas in Python: Comprehensive Study Notes

Introduction to Pandas

Pandas is an open-source Python library designed for data manipulation and analysis. It is essential for fields such as data science, artificial intelligence, machine learning, and data visualization. Pandas provides high-performance, easy-to-use data structures and tools for working with structured (tabular) data.

Core Data Structures

Pandas has two primary data structures:

  • Series: A one-dimensional labeled array. Think of it as a single column or row of data, similar to a Python list or NumPy array but with an associated index.

  • DataFrame: A two-dimensional labeled data structure. Think of it as a full spreadsheet or SQL table with rows and columns. This is the primary object you will work with.

Definition: A DataFrame is a 2D tabular data structure with labeled rows and columns, much more powerful and programmable than a native Python spreadsheet.

Key Features

  • Label-based indexing: Both row-wise and column-wise operations can be performed using labels (names) rather than just integer positions.

  • Column-wise and row-wise operations: Apply operations across entire columns or rows efficiently.

  • Support for various data types: Integers, floats, strings, dates, and more can coexist in the same DataFrame.

  • Performance: Pandas is built on top of NumPy, a fast C-based library. It is much faster than using Python lists for large datasets because it avoids Python's overhead.


Installation

To use pandas, you must install it. Open a terminal or command prompt and run:

pip install pandas

If you are on macOS or Linux, you may need to use pip3:

pip3 install pandas

Using a Virtual Environment (Optional but Recommended)

Virtual environments isolate project dependencies. One quick way to set one up is with the uv command (requires installation). Steps:

  1. Navigate to your project folder.

  2. Run uv init . to create a virtual environment in that directory.

  3. Add pandas: uv add pandas.

  4. Run your Python script using uv run filename.py.

This ensures pandas is available only inside that environment.


Importing Pandas

By common convention, import pandas with the alias pd:

import pandas as pd

This shortens the module name, making code easier to write and read.


Loading Data

The first step in most pandas workflows is to load data into a DataFrame. Pandas can read from many sources, including CSV files, Excel spreadsheets, and Python dictionaries.

From a CSV File

CSV stands for comma-separated values. Use pd.read_csv():

df = pd.read_csv('orders.csv')

This reads the file and stores it as a DataFrame.

From an Excel File

df = pd.read_excel('orders.xlsx')

From a Dictionary

Manually create a DataFrame by passing a dictionary where keys become column names and values become lists of row data:

data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Country': ['USA', 'Canada', 'UK']
}
df = pd.DataFrame(data)

This creates a DataFrame with default integer indices (0, 1, 2).


Exploring the DataFrame

Once data is loaded, you need to understand its structure. Several methods provide quick summaries.

.head() and .tail()

  • df.head() returns the first 5 rows by default. Useful for a quick preview.

  • df.tail() returns the last 5 rows.

You can pass an integer argument to see more or fewer rows, e.g., df.head(10).

.info()

df.info() gives a concise summary of the DataFrame:

  • Number of entries (rows)

  • Number of data columns

  • Column names with their data types (e.g., object, int64, float64)

  • Memory usage

Note: In the source example, columns like 'customer name' were stored as object, which is pandas' way of handling strings. Data types can be converted if needed.

.describe()

df.describe() generates descriptive statistics for numeric columns. It shows:

  • Count (number of non-null entries)

  • Mean, standard deviation, minimum, maximum

  • Percentiles: 25%, 50% (median), 75%

This helps understand the distribution and central tendency of numeric data.

.columns and .index

  • df.columns returns an index object listing all column names.

  • df.index returns an index object showing the range of row labels (e.g., RangeIndex(start=0, stop=40, step=1)).

These are useful for looping or referencing.


Indexing and Selecting Data

You can access data by columns (as Series or DataFrames) or by rows (using position- or label-based methods).

Selecting Columns

To get a single column (returns a Series):

df['country']      # or df.country

To select multiple columns (returns a DataFrame):

df[['country', 'product']]

The result is a new DataFrame containing only those columns.

Selecting Rows with .iloc

.iloc stands for integer-location indexing. It selects rows by their integer position (0-based):

df.iloc[0]      # first row, returns a Series
df.iloc[10]     # eleventh row

The returned Series can be indexed by position or by column name:

row = df.iloc[10]
row[0]          # first value (by index)
row['country']  # value in the 'country' column

To select multiple rows and columns, pass a list or slice:

df.iloc[0:5]          # first 5 rows
df.iloc[0:5, 0:3]     # first 5 rows, first 3 columns

Selecting Rows with .loc

.loc is label-based indexing. It selects rows by label (usually the index value) or by a boolean condition.

Using a condition to select rows:

df.loc[df['customer_name'] == 'Anna']

This returns a DataFrame of all rows where the condition is True.

You can also specify columns:

df.loc[df['customer_name'] == 'Anna', 'product']

This returns only the 'product' column for matching rows (as a Series).


Filtering Data

Filtering is a core operation for subsetting data based on conditions.

Single Condition

electronics = df[df['category'] == 'Electronics']

This returns all rows where the 'category' column equals 'Electronics'.

Comparison operators work similarly:

df[df['quantity'] > 20]       # greater than
df[df['quantity'] < 2]        # less than
df[df['quantity'] <= 2]       # less than or equal
df[df['quantity'] != 2]       # not equal

Multiple Conditions: AND and OR

  • AND: Use & (ampersand). Each condition must be enclosed in parentheses.

  • OR: Use | (pipe).

Example: Electronics in the USA

df[(df['category'] == 'Electronics') & (df['country'] == 'USA')]

Example: Electronics OR country is USA

df[(df['category'] == 'Electronics') | (df['country'] == 'USA')]

String Methods on Columns

Use .str accessor to apply string operations:

df[df['customer_name'].str.startswith('A')]    # names starting with 'A'
df[df['customer_name'].str.endswith('a')]      # names ending with 'a' (lowercase)

Other string methods: .contains(), .upper(), .lower(), .strip(), etc.

Using .isin() with a List

Check if a column's value is in a given list of values:

countries = ['USA', 'Sweden', 'Brazil']
df[df['country'].isin(countries)]

To negate (rows not in the list), use the tilde ~ operator:

df[~df['country'].isin(countries)]

Updating and Deleting Data

Updating with .loc

To update a specific cell or column based on a condition:

df.loc[df['customer_name'] == 'Anna', 'product'] = 'Tim'

This changes the 'product' value to 'Tim' for every row where customer_name is 'Anna'. If multiple rows match, all are updated.

You can also update multiple columns at once.

Applying a Transformation to a Column

For example, converting all country names to uppercase:

df['country'] = df['country'].str.upper()

This modifies the entire column in place.

Deleting Rows: .drop()

To remove a row by its index label:

df = df.drop(39)    # drops row with index 39

By default, .drop() returns a new DataFrame; to modify the original, use inplace=True.

Dropping Rows with Missing Values: .dropna()

If your data has null (NaN) values, you can remove rows containing them:

df.dropna(inplace=True)

Filling Missing Values: .fillna()

Instead of dropping, you can fill missing values with a specified value:

df.fillna(0, inplace=True)

This fills all NaN values with 0.

Note: inplace=True modifies the original DataFrame directly; otherwise, a new DataFrame is returned.


Renaming Columns

Use .rename() to change column names:

df.rename(columns={'order ID': 'order ID'}, inplace=True)

You can pass a dictionary mapping old names to new names. inplace=True applies the change to the existing DataFrame.


Grouping and Aggregating Data

.groupby()

Similar to SQL GROUP BY, it splits data into groups based on one or more columns, then allows you to apply aggregation functions.

Example: Sum of prices grouped by country

df.groupby('country')['price'].sum()

This returns a Series with total sales per country.

Other common aggregations: .mean(), .count(), .min(), .max(), .agg() (for multiple functions).

.value_counts()

Count the frequency of unique values in a column:

df['country'].value_counts()

Returns a Series with counts for each unique country, sorted in descending order.


Sorting Data

.sort_values() sorts the DataFrame by one or more columns.

df.sort_values('price', ascending=False)
  • ascending=True (default) sorts from smallest to largest.

  • ascending=False sorts from largest to smallest.

  • To sort by multiple columns, pass a list: df.sort_values(['country', 'price']).


Saving a DataFrame

To write a DataFrame back to a CSV file:

df.to_csv('new_orders.csv', index=False)
  • index=True (default) writes the row indices as a column.

  • index=False omits the index column, which is often cleaner for later use.

Other export options: .to_excel(), .to_json(), .to_sql(), etc.


Working in Jupyter Notebooks

Jupyter Notebooks provide an interactive environment ideal for data analysis with pandas. Cells allow you to run code incrementally, view output immediately, and keep visual context (tables, plots).

To create a Jupyter Notebook in VS Code:

  1. Press Ctrl+Shift+P (or Cmd+Shift+P on Mac).

  2. Type "New Jupyter Notebook".

  3. Save the file with a .ipynb extension.

  4. Install the Python extension if not already present (search "Python" in the Extensions pane).

Within a notebook, each cell can be run independently, and DataFrames display as nicely formatted tables.


Summary of Key Methods

Method

Purpose

pd.read_csv()

Load data from a CSV file

df.head() / df.tail()

Preview first/last rows

df.info()

Summary of columns and data types

df.describe()

Descriptive statistics for numeric columns

df.columns / df.index

Get column names / row labels

df['col']

Select a column (Series)

df[['col1','col2']]

Select multiple columns (DataFrame)

df.iloc[row]

Select row by integer position

df.loc[condition, column]

Select rows by label/condition

df[condition]

Filter rows based on condition

.str.startswith(), .endswith()

String filtering on columns

.isin(list)

Check membership in a list

~

Negate a condition

.groupby('col')['agg'].sum()

Group and aggregate

.value_counts()

Frequency of unique values

.sort_values(by)

Sort rows by column values

.dropna() / .fillna(value)

Handle missing data

.rename(columns={})

Rename columns

.to_csv()

Save DataFrame to CSV


Final Notes

Pandas is a deep library; this guide covers the fundamentals that will get you far in data analysis, cleaning, and exploration. For more advanced topics (merging, joining, time series, pivot tables, multi-indexing, performance optimization), further study is recommended. All example code from this tutorial is available in the accompanying GitHub repository.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent