Python for Data Analysis
Python for Data Analytics: Study Notes
1. Programming and Python
What programming means
Computer programming is the process of giving a computer instructions to perform an action or a sequence of actions. A programming language provides the words, symbols, and rules used to express those instructions. Different languages may be chosen for different projects or problems.
At the hardware level, computers operate through transistors that represent two states: on and off. These states are represented in binary as 1 and 0. Programming languages let people express instructions in more familiar forms; those instructions are ultimately translated into forms a computer can execute.
Low-level languages are closer to computer hardware and often require specialized knowledge.
High-level languages use more human-friendly syntax and abstract away many hardware details.
Python is a high-level, versatile programming language. It is approachable for beginners while also supporting complex work, which makes it useful in data analysis, science, web development, and other fields.
Why Python is useful for data work
Python can support many phases of a data workflow, including:
Exploring and cleaning data
Organizing and transforming data
Performing calculations and analysis
Visualizing results
Developing statistical and machine-learning models
A major reason Python is powerful is its ecosystem of libraries: reusable collections of code that provide ready-made tools for common tasks. A library can save time compared with writing every operation from scratch. Python libraries range from tools for basic mathematics to tools for advanced modeling and visualization.
Python’s broad use has also produced a large community of practitioners and resources. Coding involves building small operations into larger systems: individual lines may express simple ideas, while combinations of those lines can implement complex logic. Experimenting, practicing, and learning from errors are essential parts of becoming proficient.
2. Jupyter Notebooks and Object-Oriented Programming
Jupyter Notebooks
A Jupyter Notebook is an open-source, interactive environment for creating documents that can contain live code, output, text, mathematical formulas, and visualizations.
Notebook documents are divided into cells, which are modular input and output areas. Cells allow a user to:
Organize code into sections
Run and revise pieces of code separately
Move, add, or delete code easily
View output next to the code that produced it
Add explanations and formatted text using Markdown
This cell-based approach is especially useful for data analysis because code, results, notes, and visualizations can be kept together. In contrast, a basic terminal-based editor is often organized as a long sequence of code and may be less convenient for interactive exploration.
A notebook is stateful: cells can be run in different orders, and later code may depend on earlier cells. Therefore, the order in which cells are executed can affect the values currently stored in variables. Running an earlier assignment again may replace a value created by a later assignment.
Object-oriented programming
Object-oriented programming (OOP) organizes code around objects that contain data and functionality for working with that data.
An object is an instance of a class.
A class defines a type of object and bundles data and functionality together.
A method is a function associated with a class or object. It generally performs an operation.
An attribute is a value associated with an object or class. It describes a characteristic rather than performing an operation.
For example, a string object can have methods that change its case, replace characters, or split it into parts. A DataFrame can have attributes that describe its shape or column names.
Methods and attributes are commonly accessed with dot notation: the object name, a dot, and then the method or attribute name. Methods use parentheses because they are called; attributes do not.
Python’s built-in types include integers, floats, strings, Booleans, lists, dictionaries, tuples, sets, ranges, functions, and the special None value. Libraries can supply additional classes, and programmers can define their own.
OOP is useful because it packages data together with ways to manipulate or inspect it, encouraging organized, accessible, and reusable code.
3. Variables, Expressions, and Data Types
Variables and assignment
A variable is a named reference to a value stored in a computer’s memory. It is useful to think of a variable as a labeled container: the variable name identifies the value, but it is not itself the value.
For example, in x=3, x is the variable and 3 is its value. A meaningful name, such as age_list, is generally more informative than a name such as x.
An assignment stores a value in a variable. An expression combines values, variables, operators, or function calls and produces a result. For example, a program can find a maximum value, store that result in a variable, and then use the variable in further calculations.
Python uses dynamic typing: a variable can refer to objects of different data types at different times. A variable must generally be assigned a value before it is used. Reassigning a variable replaces the value it refers to. If a conversion or operation is intended to update a variable, its result usually needs to be assigned back to that variable.
Core data types
A data type describes the kind of data an object represents and the operations that are appropriate for it.
Integer (
int): a whole number without a fractional part.Float (
float): a number that can contain a decimal component.String (
str): a sequence of characters, usually written between single or double quotation marks.Boolean (
bool): a logical value, eitherTrueorFalse.
Python’s type function can identify the class of an object. Knowing the types involved in an operation helps explain why some operations work and others produce errors.
Combining and converting types
Some operations can combine objects of the same or compatible types. For example, numbers can be added, and strings can be concatenated. Attempting an unsupported operation, such as adding an integer to a string, causes a TypeError. Error messages provide clues about what needs to be corrected and are useful tools for debugging.
Python performs some implicit conversions automatically. For instance, in an arithmetic operation involving an integer and a float, the integer may be converted to a float so the calculation can proceed.
An explicit conversion, also called typecasting, is requested by the programmer. Common conversion functions include:
intto convert a compatible value to an integerfloatto convert a compatible value to a floatstrto convert a value to a string
A conversion produces a result; to change what a variable stores, the result generally needs to be reassigned to that variable.
4. Naming Variables and Writing Clear Code
Naming conventions and restrictions
A variable’s name should indicate what the variable stores. Clear names help the original programmer and collaborators understand the code.
Python imposes naming restrictions:
Names can contain letters, numbers, and underscores.
A name must begin with a letter or underscore, not a number.
Names cannot contain spaces, parentheses, or special characters such as
&or$.Python is case-sensitive, so capitalization changes a name.
Reserved keywords, such as
if,for,in, andelse, cannot be used as variable names.Names of existing functions, such as
printorstr, should generally be avoided because using them as variable names can obscure or replace their usual meanings.
Coding environments often highlight keywords in a distinctive color, which can help identify names that should not be used.
Parentheses and order of operations
Parentheses determine grouping in mathematical expressions. Python follows the usual mathematical order of operations: expressions inside parentheses are evaluated first, followed by the standard precedence rules for operations such as multiplication and addition.
For example, 2×(3+4)=14, while (2×3)+4=10.
5. Functions, Algorithms, and Clean Code
Functions
A function is a reusable block of code for performing a specific task. Python has built-in functions such as print, type, str, max, sorted, and len. Programmers can also define functions for tasks specific to their work.
A function definition includes:
The
defkeywordA function name
Parameters in parentheses
A colon
An indented body containing the instructions
A parameter is a named input specified in a function definition. An argument is the value supplied to a function when it is called. Python uses indentation to show which lines belong to a function or another code block. Consistent indentation is important for both correct execution and readability; four spaces is a common convention.
Functions can either display results or return them:
printdisplays information.returnsends a result out of a function so it can be saved, combined with other operations, or used later.
For example, a function can accept the base and height of a triangle and return its area:
A function can also accept hours, minutes, and seconds, calculate their total in seconds, and return the result. Because the output is returned, it can be assigned to a variable or used in another calculation.
Algorithms and decomposition
An algorithm is a set of instructions for solving a problem or completing a task. A recipe is an everyday example: it gives steps in an order that leads to a desired result. A computer program uses algorithms to tell a device how to accomplish tasks.
Thinking algorithmically means expressing a problem as logical, executable steps. A useful strategy is to break a complex problem into smaller operations, outline those operations, and then implement them one at a time.
For example, the amount of seed needed for a square grass border around a square fountain can be calculated by:
Calculating the fountain’s area.
Calculating the area of the larger square that includes the border.
Subtracting the fountain area from the larger area to find the grass area.
Multiplying the grass area by the seed rate.
Converting grams to kilograms if needed.
If the fountain’s side length is s meters and the border width is w meters, the grass area is:
At a rate of 35 grams per square meter, the seed required in kilograms is:
For s=12 and w=2, the border area is 112 square meters and the seed required is 3.92 kilograms.
Reusability, modularity, and refactoring
Reusability means defining code once and using it repeatedly rather than rewriting the same logic. When a script contains duplicated operations, a function may be able to consolidate them into a reusable unit.
Modularity is the practice of dividing code into separate components that work together. Modular code can be reused, tested, and understood more easily, and it supports collaboration on larger projects.
Refactoring is restructuring code while preserving its original functionality. Refactoring can improve names, organization, and clarity without changing what the program does.
Self-documenting code makes its purpose understandable through meaningful names, clear expressions, and logical organization. Comments supplement the code by explaining decisions or context that may not be obvious from the code itself.
Comments and docstrings
A comment is text for human readers that the computer ignores during execution. In Python, a line beginning with # is treated as a comment.
Comments can be used to:
Outline the steps of a solution before writing code
Explain why a particular decision was made
Divide a longer script into meaningful sections
Document a workflow for collaborators
A docstring is a string at the beginning of a function that summarizes what the function does, describes its parameters, and explains its return value. Docstrings help people understand how to use a function.
Clear, documented code can reduce misunderstandings and errors, make collaboration more efficient, and allow teammates to reuse work.
6. Comparators, Logical Operators, and Conditionals
Boolean values and comparators
A Boolean value represents one of two logical states: True or False. Comparisons in Python produce Boolean results.
A comparator compares two values. Python’s six common comparators test whether a value is:
Greater than another value
Greater than or equal to another value
Less than another value
Less than or equal to another value
Equal to another value
Not equal to another value
The equality comparison uses two equals signs, while one equals sign is used for assignment. Using the wrong form can cause an error or produce unintended behavior.
Comparing incompatible types can also cause a TypeError. Comparisons between strings are evaluated lexicographically: characters are compared by their order, starting with the first character and proceeding to later characters when earlier characters match.
Logical operators
Logical operators combine or modify Boolean expressions:
andisTrueonly when both component expressions areTrue.orisTruewhen at least one component expression isTrue.notreverses a Boolean value:TruebecomesFalse, andFalsebecomesTrue.
These operators allow more complex conditions to be expressed and are frequently used to make decisions about data.
Conditional branching
Branching is the ability of a program to follow different execution paths depending on conditions. Conditional statements use if, elif, and else.
An
ifstatement tests a condition. Its indented body runs only when the condition isTrue.An
elsestatement provides an alternative path when the precedingifcondition isFalse.An
elifstatement (“else if”) tests another condition when earlier conditions were not met. Multipleelifconditions can be used.
For example, a username validation function might:
Reject a username shorter than eight characters.
Reject a username longer than fifteen characters.
Accept a username that meets both length requirements.
Using elif can make several alternative conditions clearer than nesting many if and else statements. Indentation indicates which statements belong to each branch.
Modulo and a conditional example
The modulo operator gives the remainder after division. For example, 5 divided by 2 has a remainder of 1, so 5mod2=1.
An integer is even if dividing it by 2 leaves a remainder of 0. A function can test this condition and return True for an even number and False otherwise. In this type of function, an explicit else branch is optional if the function returns False after the if block.
Conditionals are useful for tasks such as validating input, grouping or “binning” data, organizing files, and controlling access based on rules.
7. Loops and Repetition
Loop terminology
A loop repeatedly executes a block of code.
An iteration is one execution of the block.
An iterable is an object whose elements can be processed in sequence.
A loop body contains the statements repeated by the loop.
Loops automate repetitive work, reducing repeated code, saving time, and lowering the chance of human error.
While loops
A while loop repeats as long as its condition evaluates to True. It is useful when repetition should continue until a condition changes.
For example, a loop can begin with x=0, continue while x<5, print the current value, and increase x by one each time. Once x reaches 5, the condition becomes false and the loop ends.
A while loop must update the condition, directly or indirectly. Otherwise, the condition may remain true indefinitely, creating an infinite loop.
A guessing game illustrates how a while loop can control a limited number of attempts:
A random number is selected.
A counter begins at zero.
The loop continues while the counter is below the maximum number of attempts.
The user’s input is converted to an integer before it is compared with the secret number.
The counter increases after each guess.
Conditional logic responds to a correct answer, an incorrect answer, or the final permitted guess.
The break keyword exits a loop immediately. A shorthand assignment such as count += 1 means the same as assigning count to its current value plus one.
For loops
A for loop iterates over the elements of a sequence or another iterable. It is often suitable when there is a collection of elements to process or when the number of iterations is known.
In a loop such as “for each value in a sequence,” the loop variable takes one element at a time. The name of that variable can be chosen by the programmer, but it must be used consistently in the loop body.
For loops can process lists, strings, and files. For example, a loop can read a text file line by line and perform an operation on each line.
The range function
The range function generates a sequence of integers. Its stop value is excluded, and if no start or step is specified, it starts at zero and increases by one.
The function can use three values:
Start: the first value in the sequence
Stop: the value at which the sequence ends, excluded from the results
Step: the amount by which values increase or decrease
For example, to include values from 0 through 100 in steps of 10, the stop value must be 101. A range from 1 to 10 produces the integers 1 through 9.
A for loop can use a range to calculate a factorial. The factorial of 9 is the product of the integers from 1 through 9:
A loop that multiplies a running product by each value in that range computes this result.
Choosing between while and for loops
Use a for loop when processing the elements of an iterable or a defined sequence of values.
Use a while loop when repeating an action until a Boolean condition changes.
When either type can solve a problem, readability and the nature of the task should guide the choice.
8. Strings
String properties and operations
A string is an immutable sequence of characters, including letters, spaces, punctuation, and other symbols. Immutability means that individual characters in an existing string cannot be changed in place. A transformed string can still be created and assigned to a variable.
Strings can be:
Concatenated: joined using the addition operator. Whitespace counts as a character, so a space must be included if words need to be separated.
Repeated: duplicated using multiplication by an integer.
Iterated over: processed character by character using a loop.
Strings cannot generally be subtracted or divided.
Escaping special characters
Quotation marks normally indicate where a string begins and ends. To include quotation marks inside a string, a different quotation style can be used around it, or a backslash can act as an escape character to change the usual interpretation of the next character.
Some combinations have special meanings. For example, \n represents a new line. If the literal characters of such a sequence are wanted instead, the backslash must itself be escaped.
Indexing and slicing
An index identifies an element’s position in an iterable. Python uses zero-based indexing, so the first item has index 0, the second has index 1, and so on.
Strings can be indexed from the left starting at 0, or from the right using negative indices:
Index −1 identifies the last character.
Index −2 identifies the second-to-last character.
Trying to access an index outside the string’s range produces an index error. The string index method returns the position of the first matching character or substring; if the requested substring is absent, it raises a value error.
A slice selects a portion of a sequence. A slice with a start and stop index includes the start but excludes the stop. Omitting the start means the slice begins at the first element; omitting the stop means it continues to the end. Slicing creates a substring without changing the original string.
The keyword in tests whether a substring occurs within a string and produces a Boolean result.
Indexing and slicing are useful for extracting or cleaning text. For example, a salary field that contains a currency symbol and digits may be read as text. Slicing can remove a prefix so the remaining characters can be converted to a numeric type for calculations.
String formatting
The format method inserts values into designated places in a larger string. Placeholders can be filled according to argument order, by named keywords, or by numbered positions. Named placeholders are useful when output components need to appear in a different order, such as when adapting text for another language.
Formatting can also control how values appear:
A format specification can limit the number of decimal places in a floating-point value, making numerical output easier to read.
Alignment specifications can line up values in columns, producing clearer tables.
Formatted output is especially useful when presenting calculation results or creating readable reports.
9. Data Structures
Data types versus data structures
A data type describes an individual kind of value, such as an integer, string, float, or Boolean. A data structure is a collection or organization of values and objects, potentially containing multiple data types.
Data structures make it possible to store, access, modify, organize, and relate data efficiently. Choosing a structure that fits the task can make analysis clearer and more effective.
Lists
A list is an ordered, mutable sequence of elements. It is written with square brackets, with elements separated by commas. A list can contain values of different types, and it can contain duplicate values.
Lists support:
Zero-based indexing and slicing
Iteration
Membership tests with
inModification, addition, and removal of elements
Common list methods include:
append: adds one element to the end of a list.insert: adds an element at a specified index.remove: removes the first matching value; trying to remove a missing value raises a ValueError.pop: removes and returns the element at a specified index.
Because lists are mutable, an element can be changed directly. This differs from strings, which are immutable and cannot have a character replaced in place.
List comprehensions
A list comprehension creates a new list by applying an expression to each element of an existing iterable. It is a compact alternative to some loops.
For example, a list of totals can be created by adding the two values in each domino tuple. The expression that creates each new element comes first, followed by the iteration over the source elements. List comprehensions can be concise and efficient, but a conventional loop may be clearer for more complex logic.
Tuples
A tuple is an ordered, immutable sequence that can contain elements of different types. Tuples are commonly written with parentheses or created with the tuple function.
Tuples are useful for records whose contents should remain fixed, such as a player’s name, age, and position. A list can hold a collection of such records, while each record is represented by a tuple:
The list can be changed by adding, removing, or rearranging records.
Each tuple keeps the fields within one record together and discourages accidental changes to them.
A tuple can be converted from another iterable, such as a list. A function that returns multiple values is effectively returning them together as a tuple. Unpacking assigns the tuple’s elements to separate variables, allowing those values to be used individually.
Tuples are iterable, so loops can unpack each tuple into variables as they process a collection. The number of variables used for unpacking must match the number of elements in each tuple.
Dictionaries
A dictionary stores key-value pairs. A key is used to look up its associated value. Dictionaries can be created with braces or with the dict function.
For example, a zoo dictionary might use pen numbers as keys and animal names as values. Looking up a key retrieves its value; looking up a value does not automatically identify its key. Attempting to access a key that is not present raises a KeyError.
Important dictionary properties and operations:
Keys must be immutable/hashable types, such as strings, integers, floats, or tuples whose contents are also suitable. Lists, sets, and dictionaries cannot be keys.
Values can hold a range of objects, including lists and tuples.
A key-value pair can be added by assigning a value to a new key.
inchecks whether a key exists; it does not check dictionary values.keys,values, anditemsprovide access to keys, values, or key-value pairs.A loop over a dictionary directly iterates over its keys.
Dictionaries are useful when data needs to be retrieved by a meaningful label rather than by position. For example, a team roster can use player positions as keys and lists of player records as values. A loop and conditional logic can build such a dictionary by checking whether each position already exists: if it does, append a player record to its value; if not, create a new entry.
Python dictionaries preserve insertion order in modern Python, but they are mappings, not sequences accessed by positional indices. If positional ordering is the main requirement, a list is generally the more suitable structure.
Sets
A set is a mutable collection of unique, unordered elements. Set elements must be immutable/hashable, so they can be stored safely in the set. Sets cannot be indexed or sliced.
A set can be created with the set function or with nonempty braces. Empty braces create a dictionary, so the set function should be used for an empty set. When an iterable is converted to a set, duplicate elements are removed. A string passed to set is treated as an iterable of characters, leaving the unique characters.
Common set operations are:
Intersection: elements shared by both sets.
Union: all elements from either set, with duplicates removed.
Difference: elements in one set but not the other. Direction matters.
Symmetric difference: elements in either set but not in both.
These operations can be expressed with methods or operators. Sets are useful when uniqueness matters or when comparing membership across collections.
Nested loops and combined structures
Structures can be combined. A list may contain tuples, and loops can process each tuple in turn. Nested loops place one loop inside another. For example, two nested loops over values from 0 through 6 can generate every pair of values for a set of domino tiles.
When a print operation normally ends with a new line, its end parameter can change that behavior, such as printing a space between items. Nested loops, lists, tuples, and formatting can be combined to generate, store, and display structured results.
10. Libraries, Packages, and Modules
Reusable code collections
A library or package is a reusable collection of code, often containing modules, functions, classes, and documentation. The terms are sometimes used interchangeably.
A module is a Python file containing code such as functions, classes, and variables. Modules organize code into reusable components that can be imported into a program.
An import statement loads a library, package, module, or selected feature into the current environment. An imported item can be given an alias, an alternate name used in the code. Standard aliases help make code concise and recognizable to other programmers.
Commonly used tools include:
math: mathematical functionsrandom: random-number generation and related operationsMatplotlib: static, animated, and interactive visualizations
Seaborn: visualization tools built on Matplotlib with a convenient interface for common plots
Scikit-learn and statsmodels: tools for statistical modeling and evaluating models
NumPy and pandas: core tools for numerical computing and data analysis
Libraries provide existing functionality, saving the programmer from repeatedly writing common operations.
11. NumPy and Arrays
NumPy and vectorization
NumPy (Numerical Python) is a library for numerical computation. It provides multidimensional arrays, matrix structures, and functions for manipulating them.
A key strength of NumPy is vectorization: applying an operation to many values at once rather than processing them one by one in a loop. For example, multiplying corresponding values in two numerical collections can be performed directly on two NumPy arrays. The result is typically shorter and clearer code, and vectorized operations can be substantially more efficient in time and memory when working with large datasets.
NumPy is commonly imported with the alias np. Importing a library allows its functions and objects to be used in the current environment; an import generally needs to be run again if that environment is restarted.
The ndarray
NumPy’s core structure is the N-dimensional array, often called an ndarray. An ndarray can be created from a Python object such as a list by passing that object to NumPy’s array function.
Key properties:
An ndarray is mutable: existing elements can be changed by index.
Its size cannot be changed in place; changing the number of elements requires creating or assigning a different array.
Its elements generally share a common data type. If incompatible types are included, NumPy may coerce them to a common type, such as converting integers to strings. Therefore, array contents should be checked when mixed data is supplied.
The array’s
dtypeattribute identifies the data type of its elements.
Dimensions, shape, and reshaping
An array’s dimension describes how its values are organized:
A one-dimensional array is a sequence of values.
A two-dimensional array can be viewed as rows and columns, like a table.
A three-dimensional array can be viewed as a collection of two-dimensional tables.
The ndim attribute reports the number of dimensions, and the shape attribute reports the size along each dimension. These properties help users understand an array and check whether it is compatible with another object or operation.
The reshape method reorganizes an array into a new shape while retaining its data, provided the requested dimensions are compatible with the number of elements. For example, an array with eight values can be reshaped from four rows and two columns to two rows and four columns.
NumPy also provides functions for common mathematical and statistical operations, including mean, logarithm, and floor and ceiling calculations. Floor rounds down to a lower whole-number boundary, while ceiling rounds up to a higher one. NumPy also supports other libraries, including pandas, so understanding arrays helps with later data analysis work.
12. pandas: DataFrames and Series
What pandas provides
pandas is a Python library for manipulating and analyzing tabular data. It is built on NumPy and is commonly imported with the alias pd.
Unlike working with arrays alone, pandas presents data in labeled rows and columns, making transformations easier to inspect. It can read data from formats such as CSV files, spreadsheets, and databases.
DataFrames
A DataFrame is a two-dimensional, labeled structure with rows and columns. It is similar to a spreadsheet or SQL table and can contain different data types in different columns.
A DataFrame can be created from several types of input, including:
A dictionary in which keys represent column names and lists provide column values
A NumPy array or nested lists
A CSV file read into pandas
A CSV (comma-separated values) file is a plain-text format in which commas separate values. pandas provides a read-CSV function that can load a file from a URL or a local file path.
Series
A Series is a one-dimensional, labeled array. Selecting an individual row or column from a DataFrame commonly produces a Series.
Inspecting pandas objects
DataFrames and Series have useful methods and attributes:
columnsprovides the column labels.shapereports the number of rows and columns.infogives structural information, including columns, data types, non-null counts, and memory use.Methods such as
mean,max,min, andstdcalculate summary statistics for suitable data.
A missing value in pandas is often represented as NaN (“not a number”). A Series containing mixed or string values may have a general object data type.
Selecting columns and rows
A single DataFrame column can be selected by its name, producing a Series. Dot notation may be used for simple column names without spaces, but bracket notation is more robust and often clearer. Multiple columns can be selected by placing a list of column names inside the selection brackets; this produces a DataFrame.
Pandas offers two important indexing approaches:
ilocselects by integer position. A single integer selects a row; a range can select several rows, and row and column positions can be specified together. In a slice, the ending position is excluded.locselects by label, such as a row or column name. When row labels are numbers, they can look like positional indices, butlocstill works by label. Label-based slices can include the ending label.
A new column can be added through assignment, using the existing DataFrame and the new column name.
13. Filtering, Grouping, and Combining pandas Data
Boolean masking
Boolean masking filters a DataFrame using a sequence of True and False values. A condition evaluated against a column produces a Boolean Series aligned with the DataFrame’s rows. Applying that Series as a mask keeps rows marked True and excludes rows marked False.
For example, a condition can select planets with fewer than a specified number of moons. Applying a mask usually produces a filtered view or result; it does not automatically permanently modify the original DataFrame. The result can be assigned to a new variable if it will be needed later.
Multiple conditions can be combined with pandas logical operators:
&means and|means or~means not
Each condition should be enclosed in parentheses when multiple conditions are combined. Parentheses make the intended evaluation clear and help avoid errors.
Grouping and aggregation
The DataFrame groupby method groups rows according to the values in one or more columns. Grouping produces a groupby object, which becomes useful when a calculation or other operation is applied to it.
Common calculations include sum, minimum, maximum, mean, median, and count. A calculation can be applied to all suitable columns or to selected columns. Grouping by multiple columns creates groups for each unique combination of values in those columns.
The agg method, short for aggregate, applies one or more calculations to groups. Existing methods can be specified alongside custom-defined functions. For example, a custom function can compute a selected percentile for each group.
Grouping and aggregation help summarize a dataset, compare categories, and prepare data for visualization. They are widely used to derive insights from tabular data.
Concatenating DataFrames
The pandas concat function joins DataFrames along an axis:
Axis 0 is vertical: data is added as rows.
Axis 1 is horizontal: data is added as columns.
Concatenation is useful when two DataFrames contain similarly structured data that should be stacked or combined. If row indices should be renumbered after adding rows, the index can be reset. The option to drop the old index prevents it from being retained as an extra column.
Merging DataFrames and join types
The merge function joins DataFrames horizontally by matching shared values called keys. The key is the common point of reference in both datasets, such as a planet name or customer identifier.
Common join types determine which keys remain:
Inner join: retains keys present in both DataFrames.
Outer join: retains all keys from both DataFrames. Missing information is filled with
NaN.Left join: retains all keys from the left DataFrame and matching keys from the right.
Right join: retains all keys from the right DataFrame and matching keys from the left.
The choice of join affects which records are included and where missing values appear. Understanding the data and the intended analysis is essential before joining tables.
14. Tidy Data and Data-Preparation Projects
Data tidying means structuring a dataset to make it easier to analyze, manipulate, model, and visualize. A common tidy-data structure follows three principles:
Each variable forms a column.
Each observation forms a row.
Each type of observational unit forms a table.
Data preparation often involves loading unstructured or inconsistently structured files, cleaning the data, and arranging it into a useful form. The purpose is not merely to make a table look orderly; a suitable structure makes later analysis more reliable and efficient.
A data professional should also be able to explain the decisions made during preparation. Documentation of the workflow helps show how the data was transformed and why particular choices were made. Such a project can demonstrate both technical skills and problem-solving to potential employers.
Communicating project work
Data professionals work with stakeholders who may have different levels of technical knowledge. Clear communication should consider:
What the audience’s goals are
What they already know
What information they need
How technical details relate to the business problem
The ability to load, clean, and structure data is valuable, but so is explaining how the work supports a decision or produces useful insight. Skills such as reasoning about business needs, documenting decisions, adapting to new tools, and communicating with different audiences are transferable across organizations and industries.

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