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

  • 91Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Pandas Selection
  • spaceFlip card
  • KI knew it
  • DI didn't know it
  • ←Previous card
  • →Next card

In the English-word dataset, what does the index represent, and what are the two data columns?

Tap to flipClick to flipspace

The index is the word itself. The columns are character count and word value, where each letter has a numeric value and the word value is the sum of its letters’ values.

Or swipe the card

91 cards

  1. In the English-word dataset, what does the index represent, and what are the two data columns?

    The index is the word itself. The columns are character count and word value, where each letter has a numeric value and the word value is the sum of its letters’ values.

  2. How can you inspect a DataFrame’s dimensions and get an overview of its index and columns?

    Use shape for the row and column counts, and info() for a summary of the index, columns, data types, and non-null counts.

  3. What does .loc select, and how can you select a row by a word used as the index?

    .loc selects by index labels. For example, df.loc['word'] retrieves the row whose index label is 'word'.

  4. What does .loc return when selecting one DataFrame row?

    It returns the selected row as a Series, rather than as a one-row DataFrame.

  5. How can .loc select several rows at once?

    Pass a list of index labels, such as df.loc[['word1', 'word2']].

  6. How can .loc select a particular column from a row or rows?

    Use its row-and-column form: df.loc[row_label_or_list, column_label_or_list].

  7. How can you find the maximum value in one numeric column or across all numeric columns?

    Use df['column'].max() for one column or df.max() for column-wise maxima across the DataFrame.

  8. What information does DataFrame.describe() provide?

    It summarizes numeric columns with statistics such as count, mean, standard deviation, minimum, quartiles, and maximum.

  9. How can you find the most common value in a Series, and how can you see the counts for all values?

    Use .mode() for the most frequent value and .value_counts() for a frequency ranking of the distinct values.

  10. What are the three main kinds of row selectors accepted by .loc?

    A single index label, a list of index labels, or a Boolean mask indicating which rows to select.

  11. How does Boolean-mask selection work in pandas?

    A condition produces a Boolean Series or array; rows with True are selected, while rows with False are excluded.

  12. How can you create a new column that is the ratio of word value to character count?

    Assign an element-wise calculation, such as df['ratio'] = df['value'] / df['char_count'].

  13. When is value_counts() less useful than a condition for finding a particular value?

    For a continuous or high-cardinality variable, a specific value may be buried among many distinct values. Filter with an exact condition instead.

  14. How can you sort a DataFrame by a column in descending order?

    Use sort_values(by='column', ascending=False). The first row then has the largest value in that column.

  15. How do you write a query() condition for a column with spaces, or refer to a variable defined outside the query?

    Surround a column name containing spaces with backticks, such as `char count`. Prefix an external variable with @, such as @threshold.

  16. How can you count rows satisfying a Boolean condition without first examining the filtered rows?

    Sum the Boolean mask: condition.sum(). In a Boolean Series, True contributes one and False contributes zero.

  17. How can you filter Pokémon with attack greater than 150 or speed of 10 or less?

    Use a condition such as df.loc[df['Attack'] > 150] or df.loc[df['Speed'] <= 10]; use .query() for equivalent simple conditions.

  18. How can you select Pokémon whose special defense is at most 25?

    Filter with df.loc[df['Sp. Def'] <= 25], then use .shape or sum the mask to count the matches.

  19. Why can a Boolean column be used directly as a row selector?

    A Boolean column already contains the True/False mask needed to choose rows; for example, df.loc[df['Legendary']] selects legendary Pokémon.

  20. How can you select non-legendary Pokémon from a Boolean Legendary column?

    Negate the Boolean mask, for example df.loc[~df['Legendary']].

  21. How do you combine two conditions to select Pokémon that are both Fire type and Flying type?

    Combine the parenthesized conditions with &, for example (df['Type 1'] == 'Fire') & (df['Type 2'] == 'Flying').

  22. What do & and | mean when combining pandas Boolean masks?

    & performs element-wise AND, so both conditions must be true. | performs element-wise OR, so either condition may be true.

  23. Why should combined Boolean conditions be parenthesized?

    Parentheses make the intended order of evaluation explicit and prevent precedence from producing unintended filter results.

  24. How can you select Pokémon that have Poison in either type column?

    Use an OR condition: (df['Type 1'] == 'Poison') | (df['Type 2'] == 'Poison').

  25. How can .isin() simplify a condition that accepts several possible values?

    Use df['column'].isin([value1, value2, ...]) instead of chaining several equality tests with OR.

  26. How can you find the Pokémon with the strongest Defense among Ice-type Pokémon?

    Filter to Ice type and sort by Defense descending, or find the maximum Defense within the filtered rows and select the matching row.

  27. How can you sort Pokémon by two criteria with different sort directions?

    Pass both column names to sort_values and provide a matching list of directions, such as ascending=[False, True].

  28. How can you find the most common primary type among legendary Pokémon?

    Filter to legendary rows, select the primary-type column, and call .value_counts(); the first result is the most frequent type.

  29. How can you filter Pokémon from the first three generations and a specified type?

    Combine the type condition with df['Generation'].isin([1, 2, 3]), then sort by the desired strength measure if needed.

  30. What is the birthday problem?

    It asks for the probability that at least one pair in a group of nnn people shares a birthday.

  31. What surprising group size gives a probability above 50% that at least two people share a birthday?

    Only 23 people are needed for the probability to exceed 50%, assuming birthdays are distributed across 365 days as in the example.

  32. How many people are needed to guarantee a shared birthday if a year has 365 possible birthdays?

    366 people, by the pigeonhole principle: at least two must share one of the 365 dates.

  33. What approximate birthday-probability calculation was used in the example?

    The example calculates 1−(364/365)(n2)1 - (364/365)^{\binom{n}{2}}1−(364/365)(2n​), using the number of pairs, (n2)\binom{n}{2}(2n​), to estimate the probability of at least one match.

  34. How many pairs can be formed from nnn people, and what is the combinations formula?

    The number is (nk)=n!k!(n−k)!\binom{n}{k} = \frac{n!}{k!(n-k)!}(kn​)=k!(n−k)!n!​. For pairs, set k=2k=2k=2, giving (n2)\binom{n}{2}(2n​).

  35. Why does the number of possible pairs grow quickly as people join a room?

    Each newly added person forms a new pair with every person already in the room, so adding one person to a group of mmm adds mmm pairs.

  36. How can Python generate all pairs of players without nested loops over birthday comparisons?

    Use itertools.combinations(players, 2) to generate each unordered pair once.

  37. How can you test which pairs share a birthday using pandas?

    Create aligned columns for the two players’ names and birthdays, then select rows where birthday1 == birthday2.

  38. Why should birthday comparisons use month and day rather than the full birth date?

    Two people share a birthday when the month and day match; their birth years do not need to match.

  39. How can pandas format a birth-date column as month and day only?

    Use the datetime string-format accessor, for example df['birth_date'].dt.strftime('%m%d').

  40. What is the Levenshtein-distance idea used for matching company names?

    It measures how different two strings are based on edit changes; a string-similarity score derived from it helps identify names that may refer to the same entity.

  41. What does a fuzzy string ratio score indicate?

    It gives a similarity score for two strings; a higher score indicates greater similarity, with 100 representing a full match in the examples.

  42. Why use a partial string ratio when comparing company names?

    A partial ratio can recognize a strong matching substring or word even when one company name contains extra text, such as a longer legal name.

  43. How can you compare every company name in one dataset with every name in another?

    Generate the Cartesian product of the two name collections, such as with itertools.product, so every name from the first set is paired with every name from the second.

  44. What columns are useful in a table of fuzzy company-name comparisons?

    Include the first source’s company name, the second source’s company name, and the computed similarity score.

  45. Why can reshaping comparisons into a DataFrame be preferable to a nested-loop-only solution?

    It creates inspectable data that can be filtered, sorted, plotted, and reviewed, making the matching process more transparent and easier to analyze.

  46. Why is a fuzzy-match cutoff score not a universal decision rule?

    Unrelated names can score highly because of shared generic words, while valid matches can score lower. The cutoff should be checked against the data and domain context.

  47. What should you do with borderline fuzzy matches during data cleaning?

    Inspect the candidate names, examine score distributions, and use domain knowledge or additional information before deciding whether the entities match.

  48. How can you identify columns with missing values in a DataFrame?

    Use df.isna().sum() to count missing values in each column; sorting the result can put the most-missing columns first.

  49. What is a quick visual way to inspect missing-data patterns?

    A missing-data visualization, such as a missingness bar chart or matrix, can reveal which columns contain missing values and how extensive they are.

  50. What rating range was treated as valid for app ratings in the example?

    Ratings were expected to be between 1 and 5; values above 5 were invalid and were set to missing.

  51. How can invalid ratings be replaced with missing values, then missing ratings filled with the mean?

    Set invalid entries to NaN, then use df['Rating'].fillna(df['Rating'].mean(), inplace=True) or assign the returned Series.

  52. When might dropping rows with other missing values be reasonable?

    When only a small number of rows have missing values in other required fields, dropping those rows may be a practical cleaning choice.

  53. Why might a column that looks numeric be read as an object/string?

    Some entries may contain nonnumeric characters or formatting, preventing pandas from parsing the entire column as numeric.

  54. How can pd.to_numeric() help find entries that cannot be parsed as numbers?

    Use pd.to_numeric(series, errors='coerce'); unparseable values become NaN, which can then be filtered for inspection.

  55. How can review counts with an M suffix be converted to numbers?

    Remove the M, convert the remaining text to numeric, and multiply by 1,000,000; convert back to a string only if required by the existing column workflow.

  56. What does duplicated() consider by default, and how can it check duplicates based only on app name?

    By default it compares whole rows. Specify subset='App' to identify repeated app names even if other columns differ.

  57. How can you mark every occurrence of a duplicated app name, including the first?

    Use duplicated(subset='App', keep=False). This marks all rows belonging to duplicated-name groups.

  58. How can you keep the app record with the greatest review count when removing duplicates?

    Sort by reviews, then call drop_duplicates(subset='App', keep='last') when the greatest review count is last in the chosen sort order.

  59. How can category labels with underscores and uppercase letters be cleaned?

    Replace underscores with spaces and apply an appropriate string capitalization method to the category column.

  60. How can install counts with commas and a trailing plus sign be converted to numeric values?

    Remove the + and comma characters, then convert the cleaned strings to numeric values.

  61. How can app sizes expressed in kilobytes or megabytes be converted to bytes?

    Remove the unit suffix, parse the numeric amount, multiply kilobytes by 1,024 or megabytes by 1,02421,024^21,0242, and handle special text values separately.

  62. How can text indicating an unavailable app size be handled in the example?

    Replace the unavailable-size text with zero before converting the cleaned size values to numeric form.

  63. How can app prices marked Free be made numeric, and how can a free/paid category be created?

    Replace Free with zero, convert prices to numeric, then label apps with price greater than zero as paid and the others as free.

  64. What general workflow helps avoid data-cleaning mistakes while modifying a DataFrame?

    Inspect and visualize the data, investigate suspicious values, keep a copy before risky changes, and retain values as strings until conversion is safe.

  65. How can an invalid season label such as ? be cleaned when season values follow a consistent pattern?

    Identify the invalid label and replace it with an explicit value such as Unknown season.

  66. How can you identify invalid goal counts in match data?

    Check the numeric data type and valid domain range, visualize the distribution, and flag values below zero because goals cannot be negative.

  67. What result values are valid in the match-result column, and how can invalid results be repaired?

    The valid categories are home win (H), draw (D), and away win (A). Recompute the result from home and away goals to replace invalid entries.

  68. How can you compute average goals per match when goals are recorded separately for the home and away teams?

    Create a per-match total by adding home goals and away goals, then take the mean of that total.

  69. How can you create a total_goals column for each match?

    Add the home-goal and away-goal columns element-wise and assign the result to a new column.

  70. How can you calculate average total goals per season?

    Group by season, take the mean of the total-goals column, and sort by the season index if chronological or label order is needed.

  71. Why use an absolute value when finding the largest goal difference regardless of which team won?

    Home goals minus away goals can be positive or negative depending on the winner; the absolute value compares the size of the difference without regard to direction.

  72. How can you find which team has the most away wins?

    Group matches by away team and count the rows whose result is an away win; sort the counts in descending order.

  73. What does a group-by operation do conceptually?

    It splits rows into groups, applies an operation to each group, and combines the group-level results.

  74. How can you find the team with the most goals scored at home?

    Group by home team, sum home goals, and sort the sums in descending order.

  75. How can you fairly compare teams by goals conceded at home when they played different numbers of home matches?

    Calculate each team’s away goals conceded at home and divide by its number of home matches; compare this per-match rate rather than raw totals.

  76. How can you find the team with the most goals scored away from home?

    Group by away team, sum away goals, and sort the totals in descending order.

  77. How do you perform a left merge of season statistics with player information when the key column names differ?

    Use merge(..., how='left', left_on='player', right_on='name') to retain all season-stat rows and attach matching player information.

  78. How can you detect rows that failed to match during a merge?

    Check whether a non-nullable field from the right-hand table, such as the player name, is missing after the merge; count those missing values with isna().sum() or a Boolean sum.

  79. Why does a missing optional field such as college not necessarily indicate a failed merge?

    The player may simply have no value recorded for that field. Use a field expected to be present, such as the player name, to diagnose merge failures.

  80. How can mismatched player names across datasets be resolved?

    Investigate the differing names, use domain knowledge to identify the same player, and update one dataset with a mapping to the name used in the other dataset before merging again.

  81. Why can a player appear more than once in season statistics, and what can a TOT team record represent?

    A player may have played for multiple teams during the season. A TOT row represents the player’s season total, so it may need to be removed when analyzing team-specific records.

  82. How can team abbreviations be converted to full team names?

    Use a mapping with the Series .replace() method to substitute each abbreviation with its full team name.

  83. How can a string birth-date column be converted to pandas datetime values?

    Use pd.to_datetime() on the birth-date column and assign the result back to the column or to a new column.

  84. How can you find the team with the most registered players in a season?

    Use value_counts() on the team column; the first entry is the team with the highest count.

  85. How can you find the team with the fewest total field goals made?

    Group by team, sum field goals for each group, and sort the sums in ascending order.

  86. How should team field-goal percentage be calculated from player-level season data?

    For each team, sum field goals made and field-goal attempts separately, then divide the team’s total makes by its total attempts.

  87. How can you compare three-point shooting accuracy by player position?

    Group by position, sum three-pointers made and attempted, divide makes by attempts for each position, and compare the resulting percentages.

  88. What does groupby(...).transform('max') do differently from a regular group-by aggregation?

    It calculates each group’s maximum and broadcasts that value back to every original row in the group, preserving the original row structure.

  89. How can you identify the top scorer for each team using a transformed group maximum?

    Create a column with groupby('team')['PTS'].transform('max'), then select rows where the player’s PTS equals that team maximum.

  90. How can the youngest team by average player age be found using birth dates?

    Group birth dates by team and calculate their mean; the team with the most recent mean birth date has the youngest average age.

  91. How can you calculate player ages numerically from birth dates if datetime means are not being used?

    Subtract each birth date from a reference date to obtain a time delta, convert that duration to days or another numeric unit, and aggregate by team.

Card 1 of 91
Card 1 of 91

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent