Pandas for Data Analysis


Pandas for Data Analysis

Simon
Welcome to Pandas by Example. The central idea is simple: you don’t become skilled at data science just by watching someone else do it. You have to practice, test your ideas, and work through real problems.

Hope
That’s the approach behind this course and Data Wars: hands-on projects broken into smaller activities, with feedback as you go. The projects build from basic DataFrame selection to cleaning, reshaping, merging, and analysis.

Simon
And there may be more than one good solution to a task. Try each activity yourself before looking at an explanation; comparing different approaches is part of learning. We’ll follow that progression, starting with a word dataset.

Hope
The word DataFrame has one row per English word, and the word itself is the index. Its columns are character count and value. Character count is the length of the word; value is the sum of its letters, with A equal to one, B equal to two, and so on.

Simon
That index choice matters. To find a row by its word, use label-based selection with `.loc`. For example, `df.loc[word]` returns the row, represented as a Series. To request just one column, use `df.loc[word, 'value']`.

Hope
Before analyzing a DataFrame, check its size and structure. `df.info()` summarizes the index, columns, data types, and non-null counts. `df.shape` returns the row and column counts. Here, the dataset contains 172,821 words.

Simon
For numerical summaries, a column can use methods such as `.max()`, `.mean()`, `.median()`, and `.mode()`. Calling `df.describe()` gives common summary statistics for numeric columns, including counts, means, minimums, and maximums.

Hope
Selection by index can take one label or a collection of labels. So `df.loc[word]` retrieves one row, while `df.loc[list_of_words]` retrieves several. You can also include a column selection, such as `df.loc[list_of_words, 'value']`.

Simon
For questions such as ‘which word has value 319?’, use a condition: `df.loc[df['value'] == 319]`. The condition produces a Boolean mask—True for rows that match and False for rows that don’t—and `.loc` selects the True rows.

Hope
That’s the key idea behind conditional selection. You can pass a single mask, several index labels, or one index label to `.loc`. Boolean masks may look large, but they’re compact Boolean data, and they’re a standard, expressive way to filter a DataFrame.

Simon
To find common values, `df['value'].mode()` gives the mode, which is 93 in this dataset. `value_counts()` is often even more informative: it ranks distinct values by frequency and tells you how often each occurs. The value 93 appears 1,965 times.

Hope
For a question like ‘what is the shortest word with value 274?’, filter first, then inspect character counts. You could sort by character count and take the shortest result, or calculate the minimum character count and filter again. During exploration, sorting can be the clearest choice.

Simon
Next, create a column by operating on existing columns. The ratio is value divided by character count, so assign `df['ratio'] = df['value'] / df['char count']`. Pandas performs the calculation across the Series, row by row.

Hope
Then the ratio column supports more questions. Its maximum is 22.5, associated with the word ‘xu’. To inspect the highest ratios, sort with `sort_values('ratio', ascending=False)`. Or filter for rows whose ratio equals the maximum.

Simon
For a ratio of 10, filter on that condition and use `.shape` to count the matching rows. There are 2,600. To find the maximum value among those rows, either sort by value or calculate the filtered value column’s maximum; both approaches answer the question.

Hope
A convenient alternative for simple conditions is `DataFrame.query()`, for example, `df.query('ratio == 10')`. If a column name contains spaces, surround it with backticks inside the query. To refer to an outside variable, prefix its name with `@`.

Simon
That’s the first project: inspecting a DataFrame, selecting by index and condition, adding a calculated column, and summarizing values. The next project uses Pokémon data to develop filtering and sorting.

Hope
Start by inspecting the data and its distributions. Histograms and box plots can reveal the shape and range of numeric statistics; counts can show how categorical values, such as Pokémon types or legendary status, are distributed.

Simon
For example, to count Pokémon with attack greater than 150, filter with `df.loc[df['Attack'] > 150]`, then use `.shape` or sum the Boolean condition. There are three. The same filtering can be expressed as `df.query('Attack > 150')`.

Hope
The Boolean-sum technique works because True counts as one and False as zero. So ` (df['Attack'] > 150).sum()` counts how many rows satisfy the condition. For speed of 10 or less, use `df['Speed'] <= 10`; that selects five Pokémon.

Simon
A Boolean column can itself be a mask. If `Legendary` contains True and False, `df.loc[df['Legendary']]` selects legendary Pokémon, and `df.loc[~df['Legendary']]` selects non-legendary ones. Understanding column types helps you understand the masks you’re using.

Hope
Sorting helps identify extreme or unusual cases. Sort by Defense descending to see the strongest defense values; you can sort by more than one column, such as Defense and then Attack, by supplying multiple sort keys.

Simon
To combine conditions, use parentheses around each comparison and use `&` for AND or `|` for OR with `.loc`. For example, Fire as type one and Flying as type two uses both conditions joined by `&`. The result is five Pokémon.

Hope
The logic is row by row. AND is True only when both conditions are True. OR is True when either condition is True. To find Poison Pokémon across either type column, combine `Type 1 == 'Poison'` and `Type 2 == 'Poison'` with `|`; there are 59.

Simon
The query syntax is a bit different: write `and` and `or`, rather than `&` and `|`. Parentheses are still useful, especially when mixing OR and AND. They make the intended order explicit and help avoid selecting the wrong rows.

Hope
To find the strongest Ice type by Defense, filter for `Type 1 == 'Ice'`, then sort Defense descending. You can also find the maximum Defense from that filtered set and select the matching row. Sorting is useful when you want to inspect the data, not just return a single value.

Simon
For the most common type among legendary Pokémon, first use the legendary Boolean mask, select `Type 1`, and call `value_counts()`. Psychic is the most common primary type in that subset.

Hope
For a Water Pokémon from generations one, two, or three, combine the type condition with a generation-membership test: `Generation.isin([1, 2, 3])`. `isin` is a compact way to express ‘is one of these values.’ Sort by Total descending to find the most powerful match.

Simon
When a condition says ‘Dragon in either type, and generation five or six,’ parentheses matter: `(Type 1 is Dragon or Type 2 is Dragon) and Generation is in [5, 6]`. Group the two type alternatives before combining them with the generation requirement.

Hope
Other tasks use the same building blocks: query for Fire Pokémon with Attack above 100; select Water primary type and Flying secondary type; or filter legendary Fire Pokémon and request only Name, Attack, and Generation. With `.loc`, the row condition comes before the comma and the chosen columns after it.

Simon
You can also select the slowest and fastest Pokémon using speed cutoffs at the fifth and ninety-fifth percentiles. Filter for speed below the lower cutoff OR above the upper cutoff. In a query, use `@` to refer to cutoff variables defined outside the expression.

Hope
And a scatter plot can help identify a Pokémon with both high Attack and high Defense. Sorting legendary Pokémon by those statistics can then help inspect likely candidates. Combining visual evidence with filtering and sorting is a useful analysis habit.

Simon
Our next project asks about the birthday problem: in a group of n people, what is the probability that at least two share a birthday? The birthday paradox says only 23 people are needed for that probability to exceed 50 percent.

Hope
It feels surprising if you focus on one person’s birthday. The important number is the number of pairs. With five people, there are ten possible pairs; adding another person adds a new pair with each person already in the room. The number of comparisons grows quickly.

Simon
The number of pairs is the combination ‘n choose 2’, which is n factorial divided by two factorial times n minus two factorial. The probability can be calculated as one minus the probability that everyone has a different birthday. A function lets us evaluate that probability for any group size.

Hope
The project then applies the idea to NBA teams. First, extract month and day from each birth date, because years don’t matter when deciding whether two players share a birthday. Pandas’ datetime string-formatting accessor can create a month-day string.

Simon
To avoid comparing every player in the entire dataset, filter to one team first. Then use combinations to generate each pair of players and each corresponding pair of birthdays. Compare the two birthday columns; matching pairs reveal shared birthdays.

Hope
The approach is worth noticing: reshape the data into pairs, then use a straightforward comparison instead of nested loops over all players. Check the scale of your result, too. A team of 22 players has 231 pairs, not 151,525—that larger number comes from choosing pairs among 551 players.

Simon
The project finds shared birthdays for several teams. For the Atlanta Hawks, the method finds three matching pairs; the Cleveland Cavaliers have one, and in the Dallas Mavericks the shared birthday pair includes JJ Barea and Deron Williams.

Hope
The wider lesson is to use domain knowledge and sanity checks. Estimate how many rows or pairs your operation should produce. If the result is wildly larger than expected, check whether you filtered to the intended team before generating combinations.

Simon
Now let’s turn to matching company names from two sources. They refer to many of the same organizations, but the strings differ: one source might use a full legal name and another a shorter form. The goal is to find likely matches.

Hope
The project uses fuzzy string similarity rather than artificial intelligence. The FuzzyWuzzy library provides similarity functions based on string distance. A partial ratio is useful when one name contains extra words, because it can match a shared portion of the text.

Simon
Instead of hiding all the work in nested loops, generate the Cartesian product of the two company-name lists with `itertools.product`. Put those pairs into a DataFrame, then calculate a partial-ratio score for every pair. The resulting table makes it possible to filter, sort, and inspect candidate matches.

Hope
The product contains 97,888 pairs in this project. For example, the two Adobe names score 100, while unrelated company names score lower. Then you can ask how many pairs meet a threshold, such as 90, and inspect likely matches for a particular organization.

Simon
But a threshold is not proof. A score of 80, for example, may match two different organizations simply because both names contain a word like ‘Corporation.’ Some pairs score 100 and are convincing; others need human review and knowledge of the organizations.

Hope
That’s why the final cleaning decision depends on context. Look at the distribution of scores, inspect the borderline cases, and ask whether city and county names, for instance, refer to the same entity in this business setting. Data cleaning requires domain knowledge, not just a clever metric.

Simon
The next project cleans scraped Google Play data. Scraping can take a long time, and repeated visits, changes to a page, or inconsistent formatting can leave missing, duplicated, or malformed values. Start with `info()` and visual checks so you know what you’re dealing with.

Hope
The dataset has 10,841 app rows. `info()` shows that several columns have missing values, while Reviews appears as an object rather than numeric. A missing-value visualization, such as a missingness bar chart, gives a quick overview; `isna().sum()` provides exact counts.

Simon
Ratings should be between zero and five in the project’s validation rule. A histogram or box plot reveals values above five, and `describe()` reports a maximum of 19. Set invalid ratings to missing, then fill missing ratings with the mean as instructed.

Hope
For other columns with only a handful of missing entries, dropping incomplete rows can be reasonable. But make that decision based on how many are affected and what information you would lose; here the number is small relative to the dataset.

Simon
Reviews looks numeric at first, but the column is stored as text and includes values such as ‘2M’. Use `pd.to_numeric(..., errors='coerce')` as a diagnostic: values that cannot be parsed become missing. Inspect those rows to discover the M suffix.

Hope
Then clean the suffix deliberately: remove M, convert the remaining value to numeric, and multiply by one million. Assign the corrected values back to Reviews. More generally, inspect unexpected values rather than assuming that a column’s appearance tells you its true data type.

Simon
Duplicates need careful definition. `duplicated()` considers all columns unless you specify a subset. To count repeated app names, use `subset='App'`. With `keep=False`, every occurrence of a repeated app is marked, rather than treating only later occurrences as duplicates.

Hope
Some repeated apps have different review counts because they may have been scraped at different times. Sort by reviews, then drop duplicates by App while keeping the last row, so the copy with the greatest review count is retained. Keep a backup before making extensive changes.

Simon
String cleaning continues with Category: replace underscores with spaces, then capitalize the text. Installs needs its plus signs and comma separators removed before conversion to numeric. These are examples of fixing representation before asking pandas to parse values.

Hope
Size combines megabytes, kilobytes, and special values such as ‘Varies with device.’ Replace the special text with zero as the project requests. For kilobytes, remove the K, convert to numeric, and multiply by 1,024; for megabytes, multiply by 1,024 twice to get bytes.

Simon
Price has dollar signs and entries marked Free. Replace Free with zero, remove the dollar sign, and convert the result to numeric. Then create a Distribution column: begin by assigning Free, and set rows with a price greater than zero to Paid.

Hope
Once those columns are clean, analysis is more straightforward. Sort by Reviews to find the most-reviewed app; use `value_counts()` for the most common category; filter and sort by Price to find the most expensive app or the most expensive game.

Simon
You can also filter Finance apps and sort by Installs to find the most installed finance app, or filter games by content rating and sort by Reviews. The important pattern is to combine a focused filter with the measure relevant to the question.

Hope
For total data transferred by the most-installed Lifestyle app, find that app, multiply its install count by its size in bytes, then convert bytes to terabytes. Be clear about units and follow the task’s rounding instruction.

Simon
A few habits make this cleaning work safer: keep copies before destructive changes; investigate conversion failures; and keep text as text until you understand and have cleaned its format. The same principle applies when parsing dates or other specialized values.

Hope
Our next dataset contains Premier League match results. Before analysis, clean the Seasons column: the expected pattern is year, dash, year, so replace question-mark entries with the specified ‘unknown season’ label.

Simon
Goals are integers, but that alone doesn’t guarantee valid data. Use the sport’s domain knowledge: goals cannot be negative. Histograms or box plots reveal values below zero; there are 34 invalid home-goal values and 39 invalid away-goal values. Replace those with zero as directed.

Hope
The Result column is categorical. Its allowed values are H for a home win, A for an away win, and D for a draw. Invalid entries can be corrected by recomputing the result from the goals: compare home and away goals, and use a draw when they’re equal.

Simon
For analysis, the average goals per match comes from adding home and away goals and taking the mean; the result is about 2.66. A `Total Goals` column stores that sum for each match, and grouping by Season lets you calculate and sort average goals per season.

Hope
To find the biggest goal difference, subtract away goals from home goals and examine the largest magnitude. The absolute value is useful when the question cares about the size of the difference, regardless of which side won.

Simon
GroupBy follows the split-apply-combine pattern: split rows into groups, calculate something for each group, then combine the results. To find the team with the most away wins, group by away team and count away-win results. Chelsea is the leader in this dataset.

Hope
The same approach finds the team with the most home goals: group by home team and sum home goals. Manchester City leads. For fewest goals conceded at home, group by home team and summarize away goals—but remember to account for how many home matches each team played.

Simon
You can use aggregation to calculate both the number of matches and goals conceded for each team, then divide goals conceded by matches. That rate makes comparisons fairer than comparing raw totals when teams have played different numbers of games.

Hope
To find the team with the most goals scored away from home, group by away team and sum away goals. Arsenal leads in the project’s dataset. These examples show how cleaning and GroupBy analysis fit together: trustworthy summaries depend on valid underlying data.

Simon
The final project combines merges, cleaning, and grouped analysis using NBA player statistics and player records. One table contains 2017 season stats; the other contains player information across NBA history. A left merge keeps every season-stat row and adds matching player details.

Hope
The join keys have different column names: the stats table uses Player, while the player table uses Name. Specify the left and right keys explicitly. After merging, check for missing names; four rows did not match, which signals a problem to investigate.

Simon
Inspect those unmatched names and compare them with the historical player table. Names can change or be recorded differently. Use the season and player context to identify the corresponding records, then map the names back to the form used in 2017 before merging again.

Hope
That investigation is data cleaning in practice. Don’t assume a mismatch means a person is absent; inspect the evidence. Also, preserve a backup before changing data, remove unnecessary columns only when you know they aren’t needed, and use the provided mapping to expand team abbreviations.

Simon
Convert birth dates from strings with `pd.to_datetime`. The dataset also includes a TOT team entry for players whose season totals cover multiple teams. Remove those total rows when the analysis requires one record per player-team stint, and check for duplicate player records deliberately.

Hope
Now the analysis: `value_counts()` on Team identifies the team with the most listed players. To find the team with the fewest field goals, group by team, sum field goals, and sort ascending.

Simon
For field-goal percentage, don’t average each player’s percentage if the question is about the team’s overall rate. Sum the team’s made shots and attempts, then divide the totals. In this dataset, the Golden State Warriors have the best field-goal percentage.

Hope
The same method works for three-point accuracy by position: group by position, sum made three-pointers and attempts, and divide the sums. Shooting guards have the highest percentage, while power forwards are lowest; the difference is about 2.4 percentage points.

Simon
A more advanced task asks for each team’s top scorer. One approach is to filter each team separately, find its maximum points, and identify the player with that score. But doing that manually for every team is cumbersome.

Hope
Instead, use `groupby('Team')['PTS'].transform('max')`. Unlike a simple aggregation that returns one row per team, `transform` broadcasts each team’s maximum back to every player row in that team. Then select rows where a player’s PTS equals that team maximum.

Simon
That gives you each team’s top scorer, along with the player, team, position, and points. It’s a powerful pattern whenever you need to compare an individual row with a group-level statistic while keeping the original rows.

Hope
Finally, to find the youngest squad by average player age, group by team and take the mean of the datetime birth-date column. The latest average birth date corresponds to the youngest average age. Portland has the youngest squad by that measure in the project.

Simon
Pandas can average datetime values directly. An alternative is to subtract each birth date from a reference date, such as the present or the season date, producing a time delta; convert that to days and average it. Either way, be clear whether a larger date means older or younger.

Hope
Across all these projects, the workflow keeps repeating: inspect structure and distributions, understand the domain, clean and reshape carefully, then select, group, summarize, or compare. Keep your intermediate results understandable, verify assumptions, and check that the scale of your answers makes sense.

Simon
And most importantly, practice. Pause on the projects, try your own solution, and compare it with alternatives. Pandas becomes much easier when you learn to turn a question into a sequence of small, testable operations.

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