Python for Data Analysis
Python Foundations for Data Professionals
1. What Python Does and Why It Is Useful
Computer programming is the process of giving a computer instructions to perform actions. A program is made from instructions written in a programming language. Different languages suit different tasks, so the language a developer chooses depends on the project and the problem to be solved.
Python is a high-level programming language. Its syntax—the rules for writing instructions—is designed to be relatively readable and human-friendly. This makes Python approachable for beginners while still giving experienced programmers tools to build complex programs.
The connection between programming languages and computer hardware helps explain why languages are needed. Computer hardware uses transistors, which operate like switches: each is either on or off. These two states can be represented as the binary digits 1 and 0. Because computers ultimately process instructions in binary, programming languages provide a way for people to express instructions in a more usable form. Low-level languages are closer to the machine’s binary operations; high-level languages such as Python make instructions easier for people to write and understand.
Python is useful in data work because it can support many stages of a data workflow: exploring, cleaning, organizing, analyzing, and visualizing data, as well as building machine-learning models. Its versatility also makes it useful in areas such as science and web development.
One major advantage is that Python is open source: its code and ecosystem are available for broad use and development. A large community has created reusable code collections called libraries or packages. Instead of writing every tool from scratch, a programmer can use an existing library for common tasks, from mathematical operations to more advanced scientific computing. This saves development time and lets data professionals focus on the problem they are solving.
Coding can be both simple and complex. Each line may express a small operation, while many lines combined can express a sophisticated process. Experimentation, practice, and learning from errors are normal parts of becoming a stronger programmer.
Python combines readable syntax with a large collection of reusable tools, making it especially valuable for exploring and analyzing data.
Think About It
Why might a high-level language be easier for people to work with than instructions written directly in binary?
2. Working in Jupyter Notebooks
A Jupyter Notebook is an open-source, interactive environment for creating and sharing documents that can include live code, its output, text, mathematical formulas, and visualizations. It is useful for data analysis because code and explanations can be kept together in one document.
A notebook is divided into cells. Each cell is a separate input-and-output area. This makes it possible to organize a project into sections, run code in manageable pieces, and revise or rearrange parts of the work. A notebook can also display results, such as tables and visualizations, alongside the code that produced them.
Notebook documents can include formatted text written in Markdown, a lightweight formatting syntax. Markdown can be used for headings, lists, tables, explanations, and mathematical notation. These explanations help readers understand a project’s purpose and workflow.
A traditional terminal-based text editor is often organized more like a long sequence of code. That approach can be suitable for many programming tasks, but notebooks offer a particularly convenient format for exploratory data work, demonstrations, and presentations.
Notebook cells can be run in different orders, so their execution order matters. A variable’s current value depends on the most recent cell that assigned or changed it. If an earlier cell is rerun, it can overwrite a value created by a later cell. For reliable results, the execution history should be considered, and the notebook should be run in a consistent order when checking the final analysis.
Think About It
How could a notebook that includes both code and explanations make a data analysis easier for a teammate to review?
3. Python Objects and Object-Oriented Programming
Python is an object-oriented programming language. In this approach, programs are organized around objects, which can combine data with code that works on that data.
An object is an instance of a class. A class defines a type of object and groups together the data and functionality associated with that type. For example, a string value belongs to the string class. Because of its class, the string has operations designed for working with text.
A method is a function associated with a class or object. Methods commonly perform an operation on the object. A string method, for example, can change the letter case of text or replace one substring with another. Methods are called using parentheses.
An attribute is a value associated with an object or class. It describes a characteristic rather than performing an operation, so it is accessed without parentheses. A DataFrame’s shape, for example, describes its number of rows and columns.
Both methods and attributes are commonly accessed through dot notation: the object’s name, a dot, and then the method or attribute name. In a notebook, a dot followed by the Tab key can often reveal available options for an object.
Python includes many built-in classes, including those for integers, floating-point numbers, strings, Boolean values, lists, dictionaries, tuples, sets, functions, ranges, and the None value. Libraries can add more classes, and programmers can define their own.
Object-oriented programming is useful because data and the tools for working with that data can be kept together. This can make code more organized, accessible, and reusable.
4. Variables, Expressions, and Data Types
Variables and assignment
A variable is a name that refers to a value stored in a program. A useful analogy is a labeled container: the label identifies what is stored, but it is not the contents itself. In an expression such as x=3, the variable name x refers to the value 3.
An assignment stores a value in a variable. The equals sign in an assignment does not ask whether two values are equal; it assigns the value on the right to the variable on the left.
country = "Brazil"
age = 30
A variable can be used wherever its value is needed. For example, it can be passed to the print function to display the value.
An expression is a combination of values, names, and operators that produces a result when evaluated. Python can evaluate arithmetic expressions, comparisons, and expressions involving variables.
print("Hello, world!")
print((5 + 4) / 3)
The first example displays text. The second performs a calculation. Operators such as +, /, and ** represent addition, division, and exponentiation. To compare whether two values are equal, Python uses ==, not the single assignment symbol =.
Data types
A data type describes the kind of value an object contains and the operations that make sense for it. Common Python data types include:
- Integer (
int): a whole number without a fractional part. - Float (
float): a number that can include a decimal part. - String (
str): a sequence of characters, usually written within single or double quotation marks. - Boolean (
bool): a value that is eitherTrueorFalse.
Python generally determines a variable’s type from the value assigned to it. This is called dynamic typing: a variable name can refer to objects of different types at different points in a program. A variable should be assigned before it is used.
The built-in type function can identify an object’s class. For example, it can distinguish an integer from a float or a string.
Converting between types
Python sometimes converts compatible values automatically. This is implicit conversion. For example, an arithmetic operation involving an integer and a float can convert the integer to a float during the calculation.
When the programmer requests a conversion, the process is called explicit conversion or typecasting. Common conversion functions include int, float, and str.
age = 30
age_text = str(age)
Assigning the conversion to age_text preserves the original variable. If the result is meant to replace a variable’s current value, the converted result must be assigned back to that variable.
Mixing incompatible types can cause a TypeError. For instance, adding an integer to a string is generally invalid: a number and a piece of text do not automatically combine as an arithmetic sum. Error messages provide clues about what went wrong. Reading them carefully is an important part of debugging, the process of identifying and fixing problems in code.
Strings are immutable, meaning their existing characters cannot be changed in place. A string operation produces a result, and that result can be assigned to a variable. This differs from a mutable object, such as a list, whose contents can be changed.
Naming variables clearly and safely
Variable names help explain what a program is storing. A name such as age_list is more informative than a name such as x, especially when the variable is encountered later or read by a colleague.
Python naming rules and common conventions help make code valid and readable. A variable name:
- Can contain letters, numbers, and underscores.
- Must begin with a letter or underscore, not a number.
- Cannot contain spaces or special characters such as
&or$. - Cannot contain parentheses.
- Is case-sensitive, so names with different capitalization are treated as different names.
Names should also avoid Python keywords, which are reserved for special language functions, such as if, for, in, and else. Existing function names, such as print and str, should also be avoided as variable names because reusing them can interfere with their intended roles. Most programming environments highlight keywords, and attempting to use one as a variable name can produce an error.
Parentheses also affect the order of mathematical operations. Python follows the standard order of operations, and an expression inside parentheses is evaluated first. Parentheses can therefore clarify an expression or change which operation happens first.
Think About It
If a variable is changed from an integer to a string, what might need to be reconsidered before the program tries to use it in a calculation?
5. Functions and Clear, Reusable Code
A function is a reusable block of code designed to perform a particular task. Python includes built-in functions such as print, type, str, max, sorted, and len. Functions can also be defined to meet the needs of a specific project.
A function definition begins with def, followed by a function name, parentheses containing any parameters, and a colon. Parameters are the names used for inputs inside the function definition. When the function is called, the values supplied to it are arguments.
def greeting(name):
print("Welcome,", name)
print("You are part of the team.")
greeting("Rebecca")
The indented lines form the function’s body. In Python, indentation indicates which lines belong to a function or another code block. Consistent indentation is essential. Four spaces per indentation level are commonly used because they make code easier to read.
A function can display a result with print, or it can send a result back to the rest of the program using return. A returned value can be stored, combined with other values, or used in another calculation.
def triangle_area(base, height):
return base * height / 2
area = triangle_area(8, 5)
Here, the function calculates a triangle’s area using its base and height. The return statement makes the result available for later use. The formula is:
A function can accept several inputs and perform multiple steps. For example, a function that receives hours, minutes, and seconds can calculate a total duration in seconds. The important design idea is that a task can be defined once and then repeated with different arguments.
This is reusability: code is written once and used many times, rather than recreated for every case. Reusable functions reduce duplication and make changes easier. If a repeated calculation needs revision, a single function can be updated rather than several copied versions.
Modularity is the practice of organizing code into separate components that work together. A function is one kind of module-like component. Modular code helps organize larger projects and makes it easier for teammates to reuse parts of one another’s work.
Algorithms, comments, and documentation
An algorithm is a set of instructions for solving a problem or completing a task. A recipe is an everyday example: it specifies a sequence of actions to produce a result. A computer program uses algorithms to direct the computer through a process.
A helpful way to design an algorithm is to break a large problem into smaller steps. Those steps can be outlined before the detailed code is written. For example, a function that calculates the amount of grass seed needed around a square fountain might be planned as follows:
- Calculate the fountain’s area.
- Calculate the total area of the fountain and surrounding square.
- Subtract the fountain’s area to find the grass area.
- Calculate the amount of seed needed for that area.
- Convert the result to the desired unit and return it.
For a square with side length s and a border of width w, the outer square has side length s+2w. Its area is (s+2w)2, while the fountain’s area is s2. The grass-border area is therefore:
(s+2w)2−s2If the seed requirement is 35 grams per square meter, the required mass in kilograms is:
1000((s+2w)2−s2)×35Comments help explain code to human readers. In Python, a comment begins with #; the interpreter ignores the text after that symbol on the same line. Comments can outline a problem’s steps, explain decisions, or clarify parts of a workflow.
A function’s docstring is a descriptive string at the beginning of its body. It summarizes the function’s behavior and explains its parameters and return value. A well-written docstring helps another programmer understand how to use the function.
Refactoring means restructuring code while keeping its original behavior. Refactoring can improve variable names, simplify expressions, reduce duplication, and make code easier to understand. Code that clearly communicates its purpose through good names and organization is often called self-documenting code. Comments and docstrings add explanations where names and structure alone are not enough.
Clear code supports collaboration. It helps teammates understand a workflow, reuse components, reduce errors, and spend less time deciphering or rewriting code.
Think About It
When a calculation appears several times in a script, why might replacing the repeated lines with a function make the program easier to maintain?
6. Comparisons, Boolean Logic, and Decisions
Comparisons allow a program to evaluate relationships between values. A comparator takes two values and produces a Boolean result: True or False. Python’s common comparison operators are:
- Greater than:
> - Greater than or equal to:
>= - Less than:
< - Less than or equal to:
<= - Equal to:
== - Not equal to:
!=
For example, a comparison can check whether a value meets a threshold. If the values are incompatible types, such as an integer and a string, the comparison may raise a TypeError.
Logical operators connect or alter Boolean expressions:
andis true only when both connected expressions are true.oris true when at least one connected expression is true.notreverses a Boolean result.
For example, an eligibility check might require both a minimum age and a completed application. An and expression would require both conditions to be true. An or expression would be appropriate if either of two conditions is sufficient.
Comparisons between strings are made in character order. Python compares the first characters, then moves to later characters if the earlier ones match. This is a character-order comparison, not a comparison of the meanings of the words.
Conditional statements and branching
Branching lets a program choose which instructions to execute based on conditions. The main branching keywords are if, elif, and else.
ifintroduces a condition. Its indented body runs only if the condition is true.elif, short for “else if,” tests another condition if earlier conditions were false.elseprovides a final alternative when no preceding condition was true.
def check_username(username):
if len(username) < 8:
print("Username is too short.")
elif len(username) > 15:
print("Username is too long.")
else:
print("Username is valid.")
In this example, the len function measures the username. The function checks the conditions in order. The elif branch avoids nesting multiple if and else blocks, making the logic easier to follow. An if statement does not require an else; if the condition is false, its body is skipped and execution continues.
The modulo operator, written % in Python, gives the remainder after division. It can be used to check whether an integer is even: an even number has a remainder of zero when divided by 2.
def is_even(number):
if number % 2 == 0:
return True
return False
The explicit else is unnecessary in this function because, if the if condition is false, execution continues to return False.
Conditional statements are useful in data work whenever processing depends on a value. They can classify or “bin” records, validate inputs, organize files, or control access according to specified rules.
Think About It
What is the difference between using and and using or when a program checks two conditions?
7. Loops and Repeated Work
A loop is a block of code that repeats. One execution of the block is an iteration. An iterable is an object whose elements can be visited one after another, such as a string, list, set, or dictionary.
Loops automate repeated work. Rather than writing the same operation for each item in a dataset, a data professional can write the operation once and let a loop apply it across the items.
while loops
A while loop repeats as long as its condition evaluates to True. The condition must eventually become false, or the loop may continue indefinitely.
x = 0
while x < 5:
print(x)
x += 1
print(x)
The variable x is initialized to 0. During each iteration, the loop prints its current value and then increments it. When x reaches 5, the condition x < 5 is false, so the loop ends and the statement after it runs.
The update inside the loop is essential. Without it, the condition might remain true forever. A while loop is especially suitable when repetition should continue until a condition changes, rather than for a predetermined number of items.
for loops and range
A for loop processes the elements of a sequence one at a time. The loop variable takes the value of the current element during each iteration.
for number in range(5):
print(number)
The range function produces a sequence of integers. With one argument, it starts at 0, increases by 1, and stops before the supplied endpoint. Thus, range(5) supplies 0, 1, 2, 3, and 4.
The function can also receive a start, stop, and step value:
for number in range(0, 101, 10):
print(number)
This sequence starts at 0, advances by 10, and stops before 101, so it includes 100. The stop value is excluded, which is why an endpoint one greater than the desired final integer is sometimes used.
A for loop is usually the clearer choice when the elements to process are already in a sequence or when the number of repetitions is known. A while loop is often the clearer choice when repetition should continue until a condition changes. Either can sometimes solve the same problem.
A loop may also be nested, with one loop inside another. The inner loop runs for each iteration of the outer loop. Nested loops can generate combinations, such as every possible pair of values from two sequences, but they should be designed carefully because the amount of work can grow quickly.
A loop can be exited early with break. For example, a guessing game can stop as soon as the user guesses correctly or reaches a maximum number of attempts. A counter can track the number of attempts. The shorthand += adds a value to a variable and assigns the result back to that variable; for example, count += 1 is equivalent to assigning count + 1 back to count.
Think About It
What must change during a while loop so the program can eventually stop repeating?
8. Working with Strings
A string is an immutable sequence of characters, such as letters, spaces, and punctuation. Strings can be combined, inspected, and sliced, even though their existing characters cannot be changed in place.
Concatenation and repetition
Concatenation joins strings. In Python, the + operator joins two strings into one. Spaces are characters, so a space must be included in one of the strings if the result should contain a gap.
The * operator can repeat a string a specified number of times. Subtraction and division are not defined for strings in the same way as for numbers.
Quotation marks mark the beginning and end of a string. To include quotation marks as text, a string can use the other style of quotation marks around it, or an escape character can be used. A backslash changes the usual interpretation of the character that follows. For example, \n represents a new line in printed output. If the literal backslash-and-n characters are intended, the backslash itself must be escaped.
Strings are iterable, so a loop can process one character at a time.
Indexing and slicing
Indexing accesses an individual element in a sequence. Python uses zero-based indexing, so the first character or item is at index 0, the second at index 1, and so on. Negative indices count backward from the end: index −1 refers to the last element.
The index string method returns the position of the first matching character or substring. If the requested text does not occur, the method raises a ValueError. Trying to access a position outside a string’s range raises an IndexError.
A slice selects a portion of a sequence. In a slice, the start position is included and the stop position is excluded. Thus, a slice from index 1 to index 4 includes indices 1, 2, and 3. If the start is omitted, the slice begins at the start of the sequence. If the stop is omitted, the slice continues to the end.
word = "orange"
print(word[1:4])
The in keyword checks whether a substring is present in a string and returns a Boolean value. These operations are useful when extracting or cleaning text. For example, if a salary field contains a currency symbol as well as digits, slicing can remove a predictable prefix before the numeric part is converted into a number. The conversion should be done only after checking that the remaining text is valid numeric data.
Formatting strings
The format method inserts values into marked positions within a larger string. Braces indicate insertion points. Values can be supplied in order, assigned explicit names, or referred to by numeric positions. Named placeholders are helpful when output order needs to change, such as when arranging a message for different languages.
Formatting can also control the appearance of numbers. For example, a format specification can limit a float to a chosen number of decimal places. A specification can also align output into columns, making a printed table easier to read.
Readable formatting matters because analysis outputs are often shared with other people. Well-formatted text and tables make results easier to interpret.
9. Data Structures: Organizing Collections of Values
A data structure is a way to collect and organize values. Data structures can contain objects of different types and provide ways to access, modify, or relate those values. The choice of structure depends on what the task requires: order, mutability, uniqueness, or lookup by a key.
Lists
A list is an ordered, mutable sequence. Lists are written with square brackets, with commas separating their elements. They can contain values of different types and can contain duplicates.
Lists support indexing and slicing, as strings do. They are useful when related values need to stay together and be processed in sequence.
Common list operations include:
append: adds one element to the end.insert: adds an element at a specified index.remove: removes the first matching value.pop: removes and returns the element at a specified index.- Assignment to an indexed position: replaces the value at that position.
An error occurs if remove is asked to remove a value that is not present. Lists can be modified in place, unlike strings.
Tuples
A tuple is an ordered, immutable sequence. It can contain values of different types and is commonly written with parentheses. Tuples are useful for grouping values that belong together but are not intended to be changed, such as a record containing a player’s name, age, and position.
A function that returns multiple values is effectively returning them together as a tuple. The values can be unpacked into separate variables:
name, age = ("Avery", 24)
After unpacking, the individual variables can be used separately. A list can contain tuples, allowing the overall collection to be modified while keeping each individual record fixed. For example, a team roster can be a list that changes as players are added, with each player represented by an unchanging tuple.
Dictionaries
A dictionary stores key-value pairs. A key identifies a value, much like a word in a conventional dictionary identifies its definition. Dictionaries are useful when values need to be retrieved by a meaningful identifier rather than by position.
Dictionaries can be created with braces or the dict function. With braces, a colon separates each key from its value, and commas separate pairs. A value is retrieved by using its key. Looking up a key that is absent raises a KeyError.
Dictionary keys must be hashable—that is, suitable for stable lookup. Common examples include strings, numbers, and tuples containing hashable values. Mutable structures such as lists and dictionaries cannot serve as keys. Dictionaries are accessed by keys, not by positional indices. If the order of records is the main concern, a list is usually a more suitable structure.
The in keyword checks for a key in a dictionary, not for a value. Useful dictionary methods include:
keys: provides the keys.values: provides the values.items: provides key-value pairs.
A loop over a dictionary processes its keys by default. A dictionary can also be constructed from another collection, such as a list of records. Conditional logic can determine whether a key already exists and whether new information should be added to its existing value.
Sets
A set stores unique, unordered elements. A set itself is mutable, but its individual elements must be hashable. A set is useful when duplicates should be removed or when membership and overlap between collections matter.
A set can be created with the set function from an iterable, such as a list, tuple, or string. Duplicate elements are reduced to a single occurrence. When a string is converted to a set, its characters become the elements, so repeated characters appear only once. A non-empty set can also be written with braces; empty braces represent a dictionary, so set() is used to create an empty set.
Sets are not accessed by positional indexing or slicing because they are unordered. Their major operations are:
- Intersection: returns elements shared by both sets.
- Union: returns all distinct elements found in either set.
- Difference: returns elements in one set but not the other; the result depends on which set is first.
- Symmetric difference: returns elements found in either set but not in both.
These operations help compare groups, such as identifying shared records, unique records, or duplicates.
List comprehensions
A list comprehension creates a new list from an existing iterable by combining a transformation with iteration in a compact form. It can often replace a longer loop that builds a list one element at a time.
Conceptually, a comprehension states the expression for each new item and then the iteration that supplies the source items. It can make simple transformations concise, though a conventional loop may be clearer when the logic is complex.
10. Libraries, Packages, and Modules
Python’s built-in features can be extended with reusable code. A library or package is a collection of related code and often documentation. The terms are sometimes used interchangeably. A module is a Python file containing code such as functions, classes, and variables. Modules organize related functionality and can be imported into a program.
An import statement loads external functionality into the current environment. For example, the math module provides mathematical functions, and random can generate random values or support random selection and shuffling.
An imported module can be given an alternate name, or alias. A common convention is to import NumPy as np and pandas as pd. Using familiar aliases makes code shorter and easier for other programmers to recognize.
Several libraries are especially relevant to data work:
- NumPy provides efficient numerical computing, including arrays and mathematical operations.
- pandas provides tools for manipulating and analyzing tabular data.
- Matplotlib supports static, animated, and interactive visualizations.
- Seaborn builds on Matplotlib and offers a convenient interface for common statistical plots.
- scikit-learn and statsmodels provide tools related to statistical and machine-learning modeling.
A library can save time because it provides tested, reusable functionality that would otherwise need to be written and maintained independently.
11. NumPy and Efficient Numerical Work
NumPy, short for Numerical Python, is a library for scientific and numerical computing. Its core data structure is the ndarray, or N-dimensional array. Arrays support efficient operations over numerical data.
NumPy’s performance is strongly connected to vectorization. Vectorization allows an operation to be applied to multiple elements together rather than writing a Python loop that processes one element at a time. For example, multiplying two same-length numerical arrays performs element-wise multiplication: the first value in one array is multiplied by the first value in the other, the second by the second, and so on.
Vectorized operations can be shorter, easier to read, faster to execute, and more memory-efficient than loops when working with large datasets.
An ndarray can be created from a list or another array-like object. Arrays are mutable, so an existing value can be changed by index. Their size cannot be changed simply by assigning an additional element; changing the array’s size requires creating or reassigning an appropriately sized array.
A NumPy array is designed to contain elements of a consistent data type. If mixed values are supplied, NumPy may convert them to a shared type when possible—for example, converting numbers to strings. This behavior matters because an unintended conversion can affect later calculations.
Several attributes help describe an array:
dtypereports the element data type.shapereports the size along each dimension.ndimreports the number of dimensions.
A one-dimensional array represents a sequence of values. A two-dimensional array can be understood as rows and columns, and a three-dimensional array can be understood as a collection of two-dimensional arrays. The reshape method reorganizes an array’s shape while keeping its data, when the requested shape is compatible with the number of elements.
NumPy also provides common mathematical and statistical operations, including calculations such as means and logarithms, as well as floor and ceiling operations. NumPy is also the foundation for tools such as pandas, so understanding its arrays helps explain how other data libraries work.
12. pandas for Tabular Data Analysis
pandas is a Python library for working with tabular data—data organized into rows and columns, like a spreadsheet or database table. It is built on NumPy and provides a convenient way to inspect and manipulate data directly as a table.
The two central pandas objects are DataFrames and Series.
A DataFrame is a two-dimensional labeled structure with rows and columns. It can contain several data types across its columns. A Series is a one-dimensional labeled structure, commonly representing one row or one column of a DataFrame.
A DataFrame can be created from a dictionary, a NumPy array, or other data structures. It can also be loaded from a CSV file. A CSV, or comma-separated values file, is a plain-text format in which commas separate values. The pandas read_csv function can load a CSV from a file path or an accessible URL.
Inspecting and selecting data
Useful DataFrame attributes and methods include:
columns, which gives the column labels.shape, which reports the number of rows and columns.info(), which summarizes column names, data types, non-null counts, and memory use.
In pandas, a missing value may appear as NaN, meaning “not a number.” A Series containing mixed or string data may have the pandas data type object.
A single column can be selected using bracket notation with the column name. Dot notation can work when the column name is a simple identifier, but bracket notation is generally more flexible and clear. Multiple columns can be selected by placing a list of column names inside brackets.
pandas provides two common ways to select rows and columns:
ilocselects by integer position.locselects by label.
For example, selecting a single row with iloc returns a Series, while selecting a list of row positions can return a DataFrame. A range selection includes the starting position and excludes the stopping position. Rows and columns can be selected together. loc selects by labels; if the row index uses numbers as labels, those labels may look like positions, but label-based selection and position-based selection remain different ideas.
A new DataFrame column can be created by assigning values to a new column name. This is a common way to add a calculated or categorized field.
Boolean masking and filtering
A Boolean mask is a sequence of True and False values used to filter a DataFrame. The mask is commonly created by comparing a column to a condition. Rows where the condition is true are retained; rows where it is false are excluded from the filtered result.
A mask can be saved in a variable for clarity or applied directly. Filtering usually produces a view or result; it does not necessarily permanently change the original DataFrame. If a filtered result will be reused, assigning it to a named variable makes that intention explicit.
Multiple conditions can be combined with pandas’ element-wise logical operators:
&means “and.”|means “or.”~means “not.”
Each individual condition should be enclosed in parentheses. For example, a filter can keep rows that meet both a numerical threshold and a separate category condition. Explicit parentheses also make the logic easier to review.
Grouping and aggregation
The groupby method groups rows according to shared values in one or more columns. It creates a groupby object, which becomes useful when a calculation or other operation is applied to it.
For example, records can be grouped by a category and then summarized using methods such as sum, min, max, mean, median, or count. The numerical columns provide the calculations, while the grouping category identifies each result row.
Grouping by multiple columns creates groups for each distinct combination of those values. For instance, data can be grouped by both product type and region to compare results for each type-region combination.
The agg method, short for aggregate, applies one or more summary calculations to groups. It can apply several existing calculations, such as mean and maximum, or a custom function. Grouping and aggregation are widely useful because they help summarize a dataset and reveal differences between categories.
Combining DataFrames
Data often comes from multiple files or sources. pandas offers tools for combining DataFrames, including concat and merge.
The concat function joins DataFrames along an axis. In a DataFrame, axis 0 runs vertically through rows, and axis 1 runs horizontally through columns. Concatenating vertically adds rows; concatenating horizontally adds columns. When adding rows from DataFrames with matching columns, resetting the index can create a fresh consecutive row numbering. An option such as drop=True prevents the old index from being added as a separate column.
The merge function joins DataFrames using shared values called keys. A key is a common point of reference, such as a planet name or customer identifier, that allows matching records from two tables.
Four common join types determine which keys remain in the result:
- Inner join: keeps only keys found in both DataFrames.
- Outer join: keeps keys found in either DataFrame.
- Left join: keeps all keys from the left DataFrame and matching keys from the right.
- Right join: keeps all keys from the right DataFrame and matching keys from the left.
When a key is missing from one side of a join, the unmatched columns in the result may contain NaN. Choosing the join type is a data-analysis decision: it determines which records are retained, so the choice should match the question being asked.
Think About It
If a report must include every record from a primary table, even when some records have no match in a second table, which join type would preserve that requirement?
13. Preparing Data for Analysis and Communicating the Work
Data professionals often receive unstructured data: data that has not yet been organized into a consistent, analysis-ready form. A common task is to load the data, clean it, and structure it for a particular business question.
A tidy dataset has a consistent arrangement:
- Each variable is a column.
- Each observation is a row.
- Each type of observational unit is represented in its own table.
This structure makes data easier to manipulate, model, and visualize. It also makes analysis more reliable because variables and observations have clear roles.
Data preparation is not only a technical task. The structure should support the business scenario the analysis is meant to address. A data professional must understand what information is needed, how the available data relates to the question, and what decisions may be supported by the result.
Documentation is part of the work. Recording the steps taken and the reasoning behind decisions helps another person understand how the dataset was prepared. It also makes it easier to explain the process in a professional setting.
Communication should suit the audience. Different stakeholders may have different levels of technical knowledge, so an explanation should take account of what the audience needs to know and what decision they are trying to make. Technical details can be translated into clear language without losing the meaning of the work.
The specific tools used may differ between organizations, but many skills transfer across settings: reasoning about a business question, preparing data, using code effectively, documenting decisions, and explaining results. Python is one useful tool for those tasks, but the broader professional skill is using data work to support informed decisions.
Comprehensive Review
Python is a readable, versatile programming language that helps data professionals automate work and analyze information. Its libraries extend its capabilities, while Jupyter Notebooks provide an interactive environment where code, output, and explanations can be organized together.
Python programs use variables to refer to values, and data types determine which operations are appropriate. Functions package reusable tasks; algorithms break problems into logical steps; comments and docstrings explain decisions and usage. Comparators and logical operators create Boolean expressions, while branching statements choose among possible actions. Loops repeat work over sequences or until conditions change.
Strings, lists, tuples, dictionaries, and sets provide different ways to organize data. Lists are ordered and mutable; tuples are ordered and immutable; dictionaries map keys to values; and sets store unique, unordered elements. Choosing the right structure depends on the requirements of the task.
NumPy supports efficient numerical operations through arrays and vectorization. pandas builds on that foundation to work with tabular data using DataFrames and Series. It supports selection, filtering, grouping, aggregation, and combining datasets. These tools help transform raw information into data that can be inspected and analyzed.
The overall workflow connects technical decisions to practical goals: understand the problem, organize and prepare the data, use clear and reusable code, check the results, and explain the work in a way that supports sound decisions.

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