1. Home
  2. Explore
  3. Computer Science
  4. Pandas for Data Analysis

Study methods

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

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.

  • shape returns the number of rows and columns as a pair. For example, a shape of (172,821,2)(172{,}821, 2)(172,821,2) means the DataFrame has 172,821172{,}821172,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:

  • loc uses labels.

  • iloc uses 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 150150150 produces one Boolean value per row. Passing that Boolean array to loc selects only the rows marked True.

Conceptually, conditional selection has two stages:

  1. Evaluate the condition for every row.

  2. 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 111 and False like 000 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∧BA \land BA∧B is true only when both AAA and BBB are true.

  • A∨BA \lor BA∨B is false only when both AAA and BBB are false.

  • ¬A\lnot A¬A has the opposite truth value of AAA.

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 and and or can 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:

ratio=valuecharacter count\text{ratio} = \frac{\text{value}}{\text{character count}}ratio=character countvalue​

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 150150150” or “speed less than or equal to 101010” create Boolean masks. The resulting rows can be inspected, counted, or saved in a new DataFrame.

The inclusive comparison is important: “101010 or less” means values that satisfy x≤10x \leq 10x≤10, not only values less than 101010.

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:

  1. Selecting the required type.

  2. Restricting generation to the allowed set.

  3. Combining those conditions.

  4. 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 nnn people, what is the probability that at least two share a birthday?

Assuming:

  • There are 365365365 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≤365n \leq 365n≤365, the probability that all birthdays are distinct is:

P(all distinct)=365365⋅364365⋅363365⋯365−n+1365P(\text{all distinct}) = \frac{365}{365} \cdot \frac{364}{365} \cdot \frac{363}{365} \cdots \frac{365-n+1}{365}P(all distinct)=365365​⋅365364​⋅365363​⋯365365−n+1​

Therefore, the exact probability that at least two people share a birthday is:

P(at least one shared birthday)=1−∏k=0n−1365−k365P(\text{at least one shared birthday}) = 1 - \prod_{k=0}^{n-1}\frac{365-k}{365}P(at least one shared birthday)=1−∏k=0n−1​365365−k​

The probability exceeds 50%50\%50% with only 232323 people. This seems surprising because there are 365365365 possible birthdays, but the number of possible pairs grows quickly as the group grows.

Number of pairs

The number of distinct pairs among nnn people is the combination:

(n2)=n!2!(n−2)!=n(n−1)2\binom{n}{2} = \frac{n!}{2!(n-2)!} = \frac{n(n-1)}{2}(2n​)=2!(n−2)!n!​=2n(n−1)​

For example, adding one person to a group creates one new pair with each person already present. A group of nnn people therefore contains (n2)\binom{n}{2}(2n​) possible pairs.

A rough approximation to the birthday probability uses the number of pairs:

P(shared birthday)≈1−(364365)(n2)P(\text{shared birthday}) \approx 1-\left(\frac{364}{365}\right)^{\binom{n}{2}}P(shared birthday)≈1−(365364​)(2n​)

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 nnn players has (n2)\binom{n}{2}(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:

  1. Filter the full data to the team of interest.

  2. Generate all two-player combinations within that team.

  3. Create corresponding combinations of birthdays in the same order.

  4. Place the paired values in a DataFrame.

  5. 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 mmm and nnn rows, the product has m×nm \times nm×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 222222 players, it has:

(222)=231\binom{22}{2}=231(222​)=231

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:

  1. Generate possible cross-dataset pairs.

  2. Calculate a similarity score for each pair.

  3. Filter to high-scoring candidates.

  4. Inspect borderline or suspicious results.

  5. 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:

  1. Inspect the distribution and descriptive statistics.

  2. Identify values outside the valid range.

  3. Mark those values as missing or otherwise invalid.

  4. 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:

  1. Identify values that fail numeric conversion.

  2. Inspect those values to determine the pattern.

  3. Remove the suffix or punctuation.

  4. Convert the cleaned text to a number.

  5. Apply the correct scale factor.

  6. Store the cleaned result in the intended column.

If a string such as 2M means two million, removing M alone would incorrectly yield 222 rather than 2,000,0002{,}000{,}0002,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:

1 KiB=1024 bytes1\ \text{KiB}=1024\ \text{bytes}1 KiB=1024 bytes
1 MiB=10242 bytes1\ \text{MiB}=1024^2\ \text{bytes}1 MiB=10242 bytes

Thus, a kilobyte value is multiplied by 102410241024, while a megabyte value is multiplied by 102421024^210242 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:

  1. Check the data type.

  2. Use domain knowledge to determine valid bounds.

  3. Visualize the distribution or inspect descriptive statistics.

  4. Select records outside the valid range.

  5. 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:

total goals=home goals+away goals\text{total goals} = \text{home goals} + \text{away goals}total goals=home goals+away goals

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:

  1. Split the DataFrame into groups, such as one group per team.

  2. Apply an operation to each group, such as a sum or count.

  3. 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:

goals conceded per home match=home goals concededhome matches\text{goals conceded per home match} = \frac{\text{home goals conceded}} {\text{home matches}}goals conceded per home match=home matcheshome goals conceded​

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:

  1. Inspect row counts and sample records.

  2. Check a key field that should be populated for every successful match.

  3. Count missing values in that field.

  4. 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:

  1. List unmatched records.

  2. Search the other dataset for likely versions of each name.

  3. Determine whether the difference is an alias, a name change, or a formatting issue.

  4. Standardize one dataset’s names to a consistent representation.

  5. 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:

field-goal percentage=total field goals madetotal field-goal attempts\text{field-goal percentage} = \frac{\text{total field goals made}} {\text{total field-goal attempts}}field-goal percentage=total field-goal attemptstotal field goals made​

The correct group calculation is:

  1. Group by team.

  2. Sum field goals made.

  3. Sum field-goal attempts.

  4. 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:

  1. Group rows by team.

  2. Calculate each team’s maximum points.

  3. Use transform() to attach that maximum to every player row in the team.

  4. Compare each player’s points with the repeated team maximum.

  5. 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:

age=reference date−birth date\text{age} = \text{reference date} - \text{birth date}age=reference date−birth 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent