Pandas for Data Analysis
Pandas for Data Analysis: Study Notes
Pandas provides tools for storing, selecting, transforming, cleaning, and summarizing tabular data. Effective analysis combines these tools with an understanding of what the data represents: a technically valid value can still be incorrect for the real-world problem.
1. DataFrames, Series, and indexes
A DataFrame is a two-dimensional table with labeled rows and columns. A Series is a one-dimensional labeled collection, usually representing one column or one selected row.
A DataFrame’s index labels its rows. The index may be a default sequence of integers, or it may hold meaningful labels such as words, player names, or dates. Understanding the index is important because label-based selection uses it directly.
Inspecting a DataFrame
Several basic methods provide an overview of a dataset:
info()reports the number of rows, column names, data types, and non-null counts. It helps identify columns that contain missing values or have unexpected types.shapereturns the number of rows and columns as a pair. For example, a shape of (172,821,2) means the DataFrame has 172,821 rows and two columns.head()displays the first few rows, making it useful for checking the table’s structure and sample values.describe()summarizes numeric columns with statistics such as count, mean, standard deviation, minimum, quartiles, and maximum.
These methods answer different questions: info() describes structure and completeness, shape gives dimensions, and describe() summarizes numeric distributions.
2. Selecting rows and columns
Pandas supports selection by index label, position, conditions, or combinations of these.
Label-based selection with loc
loc selects rows by index labels. If a DataFrame uses words as its index, a particular word can be selected directly by its label. Selecting one row generally returns a Series containing that row’s values.
loc can also select particular columns. Its general form is:
df.loc[row_labels, column_labels]The row argument can be:
One index label
A list of labels for multiple rows
A Boolean condition or Boolean array
The column argument can be one column or a list of columns. Selecting rows and columns together is more direct than selecting every column and then removing the unwanted ones.
Position-based selection with iloc
iloc selects rows and columns by integer position rather than by label. It is useful when selection depends on a row’s or column’s location in the table, not on its index label.
The distinction is:
locuses labels.ilocuses positions.
This difference matters when index labels are not the same as row positions.
Selecting multiple labels
A list of labels can be supplied to loc to select multiple rows. The selected rows are returned together, typically as a DataFrame. A list of column labels can also be supplied to return only those columns.
3. Summary statistics and frequency counts
Pandas offers methods for summarizing individual columns as well as entire DataFrames.
Maximum and other summary statistics
For a single numeric column, a method such as max() returns its largest value. Applying a summary method to a DataFrame can compute that statistic separately for each numeric column.
describe() is useful for quickly identifying:
The range of each numeric variable
Typical values, such as the mean and quartiles
Possible outliers, by comparing the maximum and minimum with the rest of the distribution
Mode and value counts
The mode is the most frequently occurring value. A column’s mode identifies its most common value, but does not by itself show how often that value occurs.
value_counts() provides a frequency table: it lists distinct values and the number of times each occurs, usually ordered from most frequent to least frequent. It is useful for:
Finding the most common category or numeric value
Comparing how frequently different values occur
Checking whether a column contains unexpected categories
A continuous numeric variable may contain many distinct values, so a frequency table can be unwieldy for such data. In that case, filtering, descriptive statistics, or visualizations may be more useful.
4. Conditional selection with Boolean arrays
A comparison applied to a pandas column produces a Boolean array: a sequence of True and False values aligned with the rows of the DataFrame.
For example, checking whether each value in an attack column exceeds 150 produces one Boolean value per row. Passing that Boolean array to loc selects only the rows marked True.
Conceptually, conditional selection has two stages:
Evaluate the condition for every row.
Retain the rows where the condition is true.
The result can be measured using its shape, or the Boolean values themselves can be summed. Since True behaves like 1 and False like 0 in this context, the sum of a Boolean condition counts how many rows satisfy it.
Combining conditions
For conditions used in a pandas selection:
AND retains a row only if both conditions are true.
OR retains a row if at least one condition is true.
NOT reverses true and false.
In Boolean terms:
A∧B is true only when both A and B are true.
A∨B is false only when both A and B are false.
¬A has the opposite truth value of A.
Pandas uses element-wise Boolean operators when combining Series. Parentheses should surround each comparison, both to make the intended grouping clear and to avoid errors caused by operator precedence.
Counting conditional matches
If a condition produces a Boolean Series, its sum gives the number of matching rows. The filtered DataFrame’s row count can also be obtained from its shape. Both approaches are useful; summing the Boolean condition can be especially concise when only a count is needed.
5. The query method
query() provides another way to filter rows using a string expression. It can make simple conditions easier to read, while loc provides a flexible way to work directly with Boolean Series.
Important query() details include:
Column names without spaces can generally be written directly in the expression.
Column names containing spaces should be enclosed in backticks.
An external Python variable can be referenced by prefixing its name with
@.Python-style logical words such as
andandorcan be used within the expression.
For instance, a query can compare a column with a threshold stored in an external variable. The external-variable marker distinguishes that variable from a column name.
Both query() and Boolean selection with loc can express the same filtering logic. The better choice depends on readability and the complexity of the analysis.
6. Sorting and identifying extremes
sort_values() orders rows according to one or more columns. By default, sorting is ascending. Setting descending order puts the largest values first, which is useful when looking for the maximum or the most powerful item.
Sorting supports several common tasks:
Finding the shortest or longest word
Identifying the highest- or lowest-scoring record
Inspecting the strongest or weakest observations
Comparing rows that meet a condition
A DataFrame can be sorted by multiple columns. The first column is the primary sorting key; subsequent columns break ties. Ascending or descending order can be set for each key separately.
Sorting versus direct calculations
There are two common ways to find an extreme:
Calculate the relevant maximum or minimum, then select the row or rows matching it.
Sort the data and inspect the first row or rows.
A direct maximum or minimum is compact and easy to use in automated calculations. Sorting provides context by showing nearby rows and their other values, which can help verify that the result makes sense.
7. Creating and transforming columns
A new column can be defined from existing columns using vectorized operations. For example, a ratio can be calculated as one numeric column divided by another:
Pandas applies such operations across the entire Series rather than requiring a Python loop over individual rows. This is generally concise and efficient.
Once created, a derived column can be used like any other column: it can be summarized, sorted, filtered, or visualized.
8. Exploratory analysis and visualizations
Before asking detailed questions of a new dataset, analysts often examine its distributions.
Useful visualizations include:
Histograms, which show the distribution of a numeric variable.
Box plots, which summarize the central distribution and help reveal potential outliers.
Bar charts, which compare category frequencies.
Visualizations help answer questions such as:
Are most observations concentrated in a narrow range?
Are there unusually large or small values?
How are categories distributed?
Do two variables appear to have an unusual relationship?
Visualization does not replace checking the underlying data. A plot can reveal a suspicious pattern, after which numeric summaries and row-level inspection can help explain it.
9. Filtering and sorting a Pokémon dataset
A Pokémon-style dataset can contain categorical columns, such as type and generation, and numeric columns, such as attack, defense, speed, and total stats. The same selection techniques apply across these variable types.
Numeric filters
Conditions such as “attack greater than 150” or “speed less than or equal to 10” create Boolean masks. The resulting rows can be inspected, counted, or saved in a new DataFrame.
The inclusive comparison is important: “10 or less” means values that satisfy x≤10, not only values less than 10.
Filtering Boolean columns
A column that already contains Boolean values can be used directly as a mask. For example, a legendary column can select legendary records without comparing it to a separate value.
Negating the Boolean Series selects the opposite group. This is useful for distinguishing records with a true status from those without it.
Filtering by type and generation
A row may need to meet conditions across multiple columns. For instance, finding Water-type Pokémon from the first three generations involves:
Selecting the required type.
Restricting generation to the allowed set.
Combining those conditions.
Sorting by a strength measure if the most powerful matching record is needed.
The isin() method checks whether each value belongs to a specified collection. It is a compact way to express “generation is one of these allowed values,” rather than writing a long sequence of OR comparisons.
Sorting by multiple properties
Sorting by defense and then attack lets the analyst rank by defense first and use attack to order ties. This is especially useful when inspecting outliers or records that have unusually high values in more than one attribute.
10. Birthday probabilities and combinatorics
The birthday problem asks: given n people, what is the probability that at least two share a birthday?
Assuming:
There are 365 possible birthdays.
Birthdays are equally likely.
People’s birthdays are independent.
Leap day is ignored.
It is easier to calculate the complement: the probability that everyone has a different birthday.
For n≤365, the probability that all birthdays are distinct is:
Therefore, the exact probability that at least two people share a birthday is:
The probability exceeds 50% with only 23 people. This seems surprising because there are 365 possible birthdays, but the number of possible pairs grows quickly as the group grows.
Number of pairs
The number of distinct pairs among n people is the combination:
For example, adding one person to a group creates one new pair with each person already present. A group of n people therefore contains (2n) possible pairs.
A rough approximation to the birthday probability uses the number of pairs:
This approximation helps explain why the probability rises quickly, but the product formula gives the exact probability under the stated assumptions.
Applying the problem to teams
A team with n players has (2n) possible player pairs. If the team’s birthdays are available as data, each player pair can be generated and their birthdays compared. This converts a question about “any pair in the group” into a row-wise comparison over a table of pairs.
For real data, the theoretical probability and the observed number of shared birthdays answer different questions:
The formula predicts a probability under uniform, independent birthday assumptions.
The dataset reveals which pairs actually share birthdays.
11. Reshaping data to compare pairs
A useful analytical strategy is to reshape data into a form that makes a question easy to express, rather than immediately writing nested loops.
Generating combinations within a group
For birthday comparisons within one team:
Filter the full data to the team of interest.
Generate all two-player combinations within that team.
Create corresponding combinations of birthdays in the same order.
Place the paired values in a DataFrame.
Compare the two birthday columns and count matching pairs.
Filtering first is essential. Generating pairs from all players when only one team is relevant produces unnecessary rows and can greatly inflate the computation.
Cartesian products across two datasets
When comparing every company in one dataset with every company in another, a Cartesian product creates every possible cross-dataset pair. If the datasets have m and n rows, the product has m×n pairs.
A product-based table makes each candidate match explicit. A score can then be calculated for every pair, after which the results can be filtered, sorted, plotted, and inspected. This is often easier to analyze than keeping all work inside deeply nested loops.
Checking the scale of a result
A rough estimate of the expected number of rows is an important debugging tool. If a team has 22 players, it has:
distinct pairs. A result with tens of thousands of rows would suggest that the data was not filtered to the intended team before pairs were generated.
12. Fuzzy matching for inconsistent strings
When two datasets contain the same organizations under different spellings, exact string equality is not enough. Differences may come from abbreviations, punctuation, suffixes, spacing, or inconsistent human entry.
Similarity scores
A fuzzy string-matching library can assign a similarity score to two strings. The underlying idea is related to edit distance: strings that require fewer edits to transform one into the other are more similar.
A partial ratio compares matching substrings, which can be useful when one name includes extra words or a longer formal name. For example, a short company name may appear inside a longer corporate name.
Similarity scores are evidence of a possible match, not proof that two records refer to the same real-world entity. A high score may result from a shared generic word, such as “Corporation,” while two organizations are otherwise unrelated.
Thresholds and manual validation
A threshold can be used to narrow candidate matches, but no threshold works perfectly for every dataset. A practical workflow is:
Generate possible cross-dataset pairs.
Calculate a similarity score for each pair.
Filter to high-scoring candidates.
Inspect borderline or suspicious results.
Use domain knowledge to decide which candidates represent the same entity.
Plotting or summarizing the score distribution helps reveal whether high scores are clearly separated from weaker matches. Records in the middle range often require more information about the organizations or the business rules.
Why reshaping supports analysis
Placing the two names and their similarity score in one table makes it possible to inspect and sort candidate matches. This structured representation makes it easier to revise thresholds and examine ambiguous cases than relying on a fixed decision buried inside a loop.
13. Cleaning app-store data
Real-world app data often contains missing values, inconsistent types, duplicated records, and values that require domain-specific interpretation.
Identifying missing values
A column’s non-null count in info() can reveal missing data. Missing values can also be counted using the isna() result and summing its Boolean values.
Libraries such as missingno can visualize patterns of missingness. A bar-style visualization shows which columns have missing entries, while inspecting counts provides a more precise view.
Missingness needs interpretation. A missing app rating may mean no users have rated the app; it does not necessarily mean the same thing as a missing category or price.
Invalid values versus missing values
A value can be present but invalid. For app ratings, values above the valid scale are not ordinary missing data, but they are inconsistent with the domain.
A suitable process is:
Inspect the distribution and descriptive statistics.
Identify values outside the valid range.
Mark those values as missing or otherwise invalid.
Decide how missing values should be handled.
If missing ratings are to be filled with the mean rating, the replacement value can be computed from the valid ratings and used to fill missing entries. That choice should reflect the analytical goal; imputing a mean is not always appropriate.
Handling non-numeric values in numeric columns
A column may look numeric but be stored as text because some entries contain extra characters. A numeric conversion with coercion can convert unparseable values to missing values, helping identify which rows need cleaning.
For example, a review count may contain an M suffix to indicate millions. A robust process is:
Identify values that fail numeric conversion.
Inspect those values to determine the pattern.
Remove the suffix or punctuation.
Convert the cleaned text to a number.
Apply the correct scale factor.
Store the cleaned result in the intended column.
If a string such as 2M means two million, removing M alone would incorrectly yield 2 rather than 2,000,000. The suffix’s meaning must be preserved in the conversion.
Duplicate records
Duplicate detection can operate on entire rows or on selected columns:
Whole-row duplicates require all compared column values to match.
Duplicates based on an app name can be detected by specifying the app column as the subset.
By default, duplicate detection may mark later occurrences while leaving the first occurrence unmarked. An option to mark all copies can make every repeated occurrence visible.
If records were collected at different times, they may share an app name but differ in review counts or other changing information. Sorting by a measure of freshness, such as review count when that is justified, and retaining the appropriate occurrence can help reduce duplicates. The decision depends on how the data was collected and how the chosen measure changes over time.
Standardizing text
String operations can standardize category labels by:
Replacing underscores with spaces
Changing letter case
Removing unwanted symbols
Making similar labels consistent
Standardization makes categories easier to group and compare, but it should preserve meaningful distinctions.
Converting installs
Install counts may contain commas or a trailing plus sign. These characters should be removed or interpreted before numeric conversion. After cleaning, the column can be converted to a numeric type.
Converting app sizes to bytes
App sizes may be reported in megabytes, kilobytes, or as a special value such as “Varies with device.” A consistent numeric representation requires handling each case explicitly.
For binary units:
Thus, a kilobyte value is multiplied by 1024, while a megabyte value is multiplied by 10242 to express it in bytes. Special text such as “Varies with device” cannot be converted directly to a single numeric size; it needs a deliberate rule, such as recording it as missing or assigning a specified placeholder.
Cleaning prices and identifying paid apps
Price values may contain a currency symbol, while free apps may be labeled with text rather than a numeric zero. A consistent process converts free values to zero, removes currency symbols from paid values, and converts the cleaned result to numeric form.
A separate category such as “free” or “paid” can then be derived from the numeric price. This makes it easier to compare app groups without repeatedly interpreting the raw price field.
Analysis after cleaning
Once the relevant columns are clean and consistent, they can be used for questions such as:
Which app has the most reviews?
Which category has the most apps?
Which paid game has the most reviews?
Which finance app has the most installs?
How much data might be transferred by an app, estimated as installs multiplied by app size?
A transfer estimate based on installs and size is an approximation. It assumes that each install corresponds to a transfer of the listed size, which may not reflect real usage or actual network traffic.
14. Cleaning football match data
Football match data illustrates several different kinds of validation: pattern checks, numeric ranges, categorical values, and values that can be recomputed from other columns.
Season labels
A season label may follow a pattern such as a four-digit year, a separator, and the following four-digit year. A placeholder such as a question mark does not match that pattern and should be replaced with an explicit unknown value or handled as missing.
The correct replacement depends on how downstream analyses should treat records with unknown seasons.
Validating goal counts
Home goals and away goals should be numeric integers. That alone does not guarantee validity: a negative goal count is outside the valid range of football scores.
A useful validation sequence is:
Check the data type.
Use domain knowledge to determine valid bounds.
Visualize the distribution or inspect descriptive statistics.
Select records outside the valid range.
Decide whether to correct, remove, or otherwise handle them.
Negative goals can be identified with a condition and counted by summing the resulting Boolean values. If a known cleaning rule specifies replacing invalid negative values with zero, the same conditional selection can assign zero to those rows.
Recomputing match results
A result column may contain categories such as home win, draw, and away win. If the result can be derived from the goals, the result can be checked or reconstructed:
Home goals greater than away goals implies a home win.
Away goals greater than home goals implies an away win.
Equal goal counts imply a draw.
Recomputing the result from the two score columns can replace invalid labels and ensure internal consistency.
Creating total goals
A total-goals column is a derived feature:
The average number of goals per match can then be calculated from this column, or from the sum of the home-goal and away-goal Series.
15. GroupBy: splitting, applying, and combining
The GroupBy pattern separates data into groups based on one or more keys, performs operations within each group, and combines the results.
This is often described as split–apply–combine:
Split the DataFrame into groups, such as one group per team.
Apply an operation to each group, such as a sum or count.
Combine the group results into a new Series or DataFrame.
Aggregating match data
Grouping match data by season and calculating the mean of total goals gives average goals per season. Grouping by a team and summing goal counts gives total goals scored or conceded by that team.
Sorting the result helps identify the highest or lowest team, season, or statistic.
Counting away wins
To find which team has the most away wins, the data can first be filtered to away victories and then grouped by the away-team column. Counting rows in each group yields the number of away wins per team.
Another approach groups all matches by away team and applies a function that counts only away-win results in each group. Filtering first is often easier to read; a custom group function can be useful when several calculations must be performed within each group.
Comparing teams fairly
The team with the fewest goals conceded at home is not necessarily the team with the best defensive rate. Teams may have played different numbers of home matches.
For a fair comparison, calculate both:
Total goals conceded at home
Number of home matches played
Then compute the rate:
This illustrates a general analytical principle: totals can be misleading when groups have different sizes, exposure, or opportunities. A rate or average may be more appropriate.
16. Merging datasets
A merge combines rows from two DataFrames using related columns or indexes. The correct join type depends on which records must be preserved.
Left merge
A left merge preserves every row from the left DataFrame and adds matching information from the right DataFrame. If there is no right-side match, the added fields are missing.
This is useful when one dataset is the primary record of interest—for example, a particular season’s player statistics—and the other contains supplementary information such as player height or birth date.
The key columns do not need to have the same names. The merge can explicitly specify the left-side key and the right-side key.
Checking merge quality
After a merge:
Inspect row counts and sample records.
Check a key field that should be populated for every successful match.
Count missing values in that field.
Investigate the unmatched records.
A missing supplementary field does not always mean the merge failed: some personal attributes, such as college, may genuinely be unknown. A missing merge key or expected identity field is a stronger sign of a mismatch.
Fixing mismatched names
Names can change, be abbreviated, or be written differently across datasets. Resolving those mismatches may require domain knowledge and inspection of individual records.
A practical approach is to:
List unmatched records.
Search the other dataset for likely versions of each name.
Determine whether the difference is an alias, a name change, or a formatting issue.
Standardize one dataset’s names to a consistent representation.
Perform the merge again and verify that the mismatches have been resolved.
Mappings are useful when the set of known name changes is finite and explicit. Investigating first is important: blindly changing names can create false matches.
17. Additional DataFrame operations
Dropping columns
Columns that are not needed for the analysis can be removed. Explicitly listing the columns to drop makes the change clear and reduces distractions in later analysis.
Replacing abbreviations
A mapping can replace team abbreviations with full names. This makes reports easier to read and standardizes team labels across operations.
Backing up data during cleaning
Cleaning often involves several irreversible transformations. Keeping a copy of the DataFrame before a major change makes it possible to return to an earlier state if an assumption proves wrong.
Copies are especially useful during exploratory work, but they consume memory. Large datasets may require saving checkpoints to storage or using a more selective backup strategy.
Removing aggregate rows
Some player datasets include a special total row, such as a player’s combined season statistics across teams. If the analysis requires one row per actual team-player record, these aggregate rows should be removed. Otherwise, totals can be counted twice when grouped or merged.
18. Grouped percentages and rates
A percentage built from counts should generally be calculated from the group’s aggregated numerator and denominator.
For team field-goal percentage:
The correct group calculation is:
Group by team.
Sum field goals made.
Sum field-goal attempts.
Divide the two group totals.
Averaging each player’s individual percentage would give equal weight to a player with few attempts and a player with many attempts. That may not represent the team’s overall shooting accuracy.
The same principle applies to three-point accuracy by position or team: aggregate made shots and attempts separately, then divide.
19. transform() for group-level values on individual rows
GroupBy transform() calculates a group-level result and returns a Series aligned to the original rows. The result has the same row structure as the input, with the group-level value repeated for each member of that group.
For example, to identify each team’s highest-scoring player:
Group rows by team.
Calculate each team’s maximum points.
Use
transform()to attach that maximum to every player row in the team.Compare each player’s points with the repeated team maximum.
Keep rows where the two values match.
This differs from a standard aggregation:
An aggregation returns one row per group.
A transform returns one value per original row, aligned with that row.
The method is useful when each record needs to be compared against a statistic for its own group.
20. Datetime data and player ages
Dates should be represented as datetime values when date-aware operations are needed. Converting a birth-date column from text to a datetime type enables date differences, sorting, and other temporal calculations.
Average birth dates
A mean can be computed over datetime values. For each team, the mean birth date summarizes the group’s birth dates. The team with the most recent average birth date has the youngest roster on average, assuming the same reference date.
However, average birth dates can be less intuitive than average ages. A direct age calculation requires a reference date:
The resulting time difference can be expressed in days or another time unit and averaged by team. For reproducible analysis, the reference date should be fixed, such as the end of the season being studied, rather than using the current date every time the analysis runs.
21. General principles for practical analysis
Several habits recur across the examples:
Inspect before transforming. Check sample rows, types, counts, and distributions before assuming the data is clean.
Use domain knowledge. Validity depends on what a value represents; numeric type alone does not establish that a value is meaningful.
Validate intermediate results. Check counts, ranges, row shapes, and representative records as each operation is performed.
Use vectorized operations where possible. Column-wise comparisons and arithmetic are often clearer than explicit row-by-row loops.
Reshape data to make questions easier to express. Pair tables, candidate-match tables, and grouped summaries can make analysis more transparent.
Choose denominators carefully. Rates are often more informative than totals when groups have different numbers of observations.
Treat automated matching as candidate generation. Similarity scores and thresholds narrow the search, but ambiguous cases still need validation.
Preserve meaning during cleaning. Removing a suffix, punctuation mark, or unit indicator without applying its meaning can produce incorrect values.
Keep an auditable process. Clear transformations and backups help diagnose mistakes and make results reproducible.
Pandas is most effective when its selection, transformation, grouping, and cleaning methods are paired with careful reasoning about how the data was created and what each value means.

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