1. Home
  2. Explore
  3. Computer Science
  4. Python Data Analysis

Study methods

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

Python Data Analysis

Speaker 1Speaker 2

Python Data Analysis

13:50
0:00-13:50
  1. Hope

    Welcome back to the show. Today we're learning a practical workflow for exploring a brand-new data set with Python and pandas. Maria, where should someone begin if they're completely new to this?

  2. Maria

    The material recommends starting with an introductory pandas tutorial first if you're entirely new to Python and pandas. The demonstration takes place in a Kaggle notebook, which is similar to a Jupyter notebook: you can run code in cells and write plain-text descriptions around that code. Because Kaggle provides the environment, you do not need to install Python on your own computer. You can fork or copy the notebook and follow along.

  3. Hope

    And the example data set is about roller coasters, right?

  4. Maria

    Exactly. It contains information about more than a thousand roller coasters, including things such as speed, height, material, location, and other characteristics. If you want to use another data set in Kaggle, you can select Add Data, choose an existing data set, or upload your own. On your own machine, you would simply reference the CSV file you want to analyze.

  5. Hope

    Before loading anything, the notebook sets up the main tools. Pandas is imported as pd, NumPy as np, matplotlib's plotting interface as plot, and seaborn as sns. Matplotlib and seaborn will be especially useful once we begin visual exploration.

  6. Maria

    There are also two useful settings. First, the matplotlib style is set to ggplot with plot.style.use, giving the plots a consistent appearance. Second, pandas is configured with pd.set_option to display up to 200 columns. That matters when a data frame has many columns, because pandas otherwise replaces some of them with dots in the notebook output.

  7. Hope

    Then the data is loaded into a data frame called df with pd.read_csv. In the example, the file is in Kaggle's input folder and is named coasterdb.

  8. Maria

    Once the data is loaded, the first phase is basic data understanding. A very simple but important command is df.shape. It reports the number of rows and columns. In the initial data set, that output is 1,087 rows and 56 columns.

  9. Hope

    And df.head lets you preview the first five rows by default. You can pass a number, such as df.head(20), to display the first 20 rows. The preview helps you see the columns and get a quick sense of the values.

  10. Maria

    If the data frame has many columns, setting the maximum displayed columns to 200 makes that preview much more useful. You can also use df.columns to list every column name. That becomes important when deciding which columns to retain and which ones to remove.

  11. Hope

    Next comes data types. In pandas, every data-frame column is a Series, and every Series has a data type. Running df.dtypes shows the type pandas assigned to each column. In this data set, many columns are object types, which represent strings, while the numeric roller-coaster features use types such as integers or floating-point values.

  12. Maria

    The final basic-understanding command is df.describe. It summarizes the numeric columns with statistics such as count, mean, standard deviation, minimum, quartiles, and maximum. For example, the height column has 171 available values and an average of about 101 feet. This is a quick way to understand the numeric data before doing deeper analysis.

  13. Hope

    After that initial inspection comes data preparation. The key principle is to decide which rows and columns you actually need before spending time cleaning everything. Otherwise, you may clean columns that will later be discarded.

  14. Maria

    The roller-coaster data contains both text versions and cleaned numeric versions of some measurements. For example, one speed column contains strings such as values with miles per hour attached, while another contains numeric miles-per-hour values. The same idea applies to height and some other measurements. For analysis, the numeric versions are generally the useful ones.

  15. Hope

    There are two demonstrated ways to remove unwanted columns. The first is to create a list of the columns you want and select them with two sets of brackets, like df followed by the list of column names. You can comment out names you do not want, which makes the selection easy to review.

  16. Maria

    The second method is drop. For example, df.drop can remove one column or a list of columns. When removing a column, you specify axis=1, because axis zero refers to rows and axis one refers to columns. In the example, dropping Opening Date makes that column disappear.

  17. Hope

    For the main cleaning workflow, the demonstration selects a deliberate subset of columns and reassigns it to df. The retained information includes the coaster name, location, status, material type, opening date, year introduced, latitude, longitude, and cleaned numeric features such as speed, height, inversions, and g-force.

  18. Maria

    The selection ends with .copy(). That tells pandas this is a new data frame rather than merely a reference to the old one. It is useful when you plan to manipulate the resulting data frame later. After this step, the data still has 1,087 rows, but only 13 columns.

  19. Hope

    Data types may need correction after subsetting. Opening Date is showing as an object, even though it represents dates, so pd.to_datetime converts it into a datetime64 type.

  20. Maria

    There is a similar conversion for numeric data. If a numeric-looking column were stored as strings, pd.to_numeric could ask pandas to convert it into a numeric type. Year Introduced is already an integer in this example, so that conversion is not necessary there, but it is a useful technique to know.

  21. Hope

    Column names can also be cleaned up. The rename method accepts a dictionary mapping old names to new names. The example changes names so they use a more consistent uppercase-first-letter format and removes the word Clean from names that now refer to the only retained version.

  22. Maria

    The updated data frame is then reassigned to df, and another head preview confirms that the names look consistent. It is also helpful that the names do not contain spaces, because names without spaces are easier to work with in code.

  23. Hope

    Now we need to investigate missing values. Calling df.isna produces a true-or-false value for every cell, indicating whether that cell is null. That raw result can be overwhelming, so adding sum counts the missing values in each column.

  24. Maria

    For this data set, status is missing in 213 rows, and latitude, longitude, and g-force also have missing values. The important point is that we now know where missingness occurs before deciding how to handle it.

  25. Hope

    The next data-quality check is duplication. df.duplicated marks repeated rows. By default, it marks the second and any later occurrence as true while leaving the first occurrence unmarked. Selecting those true values with .loc lets you inspect the duplicated rows.

  26. Maria

    There are no completely identical rows in the example. But duplicates can also be checked using only selected columns. For instance, checking a subset containing Coaster Name reveals repeated coaster names. There are 97 repeated names.

  27. Hope

    Repeated names do not automatically mean the records are errors. The example examines Crystal Beach Cyclone with df.query, filtering for rows whose Coaster Name equals that coaster. Most values match, but the Year Introduced values differ. That could indicate an error, or it could reflect a coaster being opened, taken offline, and later reopened.

  28. Maria

    For the analysis, the goal is to keep one record when Coaster Name, Location, and Opening Date are duplicated. The duplicated method can take that subset of columns, and placing a tilde before the result reverses the true and false values. That keeps the first version of each repeated combination rather than the later duplicates.

  29. Hope

    Because rows have been removed, the original index may no longer increase consecutively. reset_index repairs that sequence. Adding drop=True prevents pandas from preserving the old index as an extra column.

  30. Maria

    After saving the cleaned result back into df, the data contains 990 unique roller coasters and 13 feature columns. At this point, the data is prepared well enough to explore the features themselves.

  31. Hope

    Examining one feature at a time is called univariate analysis. It helps reveal distributions and possible outliers. For a categorical or discrete numeric column such as Year Introduced, value_counts is especially useful because it counts how often each unique value occurs.

  32. Maria

    The counts are ordered from most common to least common. In this example, 1999 is the most common year, with 46 roller coasters introduced, followed by 2000 and 1998. That gives us an immediate sense of which years occur most often.

  33. Hope

    Those counts can also be visualized. Taking the first ten results with head and plotting them as a bar chart shows the top ten years for coaster introductions. A title and axis labels make the result interpretable: the x-axis can be Year Introduced, and the y-axis can be Count.

  34. Maria

    The backslashes used in the example simply allow a long line of Python to be split across several lines. They do not change the operation; they just make the code easier to read.

  35. Hope

    For a continuous numeric feature such as Speed in Miles per Hour, a histogram is useful. A histogram divides the values into bins and shows how many observations fall into each bin. The example uses 20 bins, adds a title, and labels the x-axis with the speed measurement.

  36. Maria

    The speed histogram suggests that speeds around 40 to 50 miles per hour are common, with a particularly noticeable concentration around that range. It also shows some values far out toward the high end, which could be worth investigating as potential outliers. Since early roller coasters often lack speed information, missing values are part of the interpretation.

  37. Hope

    A related option is a kernel density estimate, or KDE, plot. It provides a smoother view of the distribution and can be less cluttered, especially when comparing multiple distributions. For coaster speed, the KDE shows noticeable humps around roughly 35 and 50 miles per hour.

  38. Maria

    The recommendation is to examine this kind of distribution for every feature when performing exploratory data analysis. Each feature may reveal its own common values, unusual observations, or missing-data patterns.

  39. Hope

    The next level is feature relationships, or comparing columns with one another. A scatter plot compares two numeric features, such as Speed in Miles per Hour on the x-axis and Height in Feet on the y-axis. Each dot represents a row in the data set.

  40. Maria

    The pandas plotting method can create that scatter plot, and plot.show produces a cleaner display in the notebook instead of printing the underlying matplotlib object information. A title such as Coaster Speed Versus Height helps explain what the chart shows.

  41. Hope

    Seaborn can create a similar scatter plot with more flexibility. Its scatterplot function takes x, y, and data arguments. The example uses the same speed and height columns with df as the data frame.

  42. Maria

    Seaborn also lets another variable control the point color through hue. When Year Introduced is used as hue, the scatter plot shows how the speed-height relationship varies across introduction years. The function documentation can be viewed interactively in a notebook by placing the cursor inside the function and using Shift-Tab.

  43. Hope

    What if we want to compare more than two features at once?

  44. Maria

    That is where seaborn's pairplot is useful. It creates a matrix of comparisons for the selected features. Off the diagonal, you see pairwise scatter plots; along the diagonal, you see the distribution of each individual feature. Adding hue, such as the type of material used, colors the points according to that additional variable.

  45. Hope

    That colored pair plot can reveal patterns that are difficult to see in one chart. For example, the material colors show that early roller coasters contain little steel, while steel begins appearing around the 1950s and becomes increasingly common later.

  46. Maria

    Another way to compare numeric features is correlation. Select the numeric columns, remove null rows, and call corr. The result contains a correlation value for each pair. In the example, speed and height have a correlation of about 0.73, while some pairs have negative correlations and Year Introduced does not show a strong relationship with the other features.

  47. Hope

    A correlation heat map makes that table easier to scan. Seaborn's heatmap accepts the correlation data frame, and setting annotations to true displays the raw correlation values inside the cells. The diagonal contains ones because every feature has a perfect correlation with itself.

  48. Maria

    The final stage is to ask a question that the data can answer. Rather than making plots without a purpose, the example asks: which locations have the fastest roller coasters, considering only locations with at least ten coasters?

  49. Hope

    The first step is to inspect Location with value_counts. One value is Other, which does not represent a specific location, so the analysis filters it out with a query stating that Location does not equal Other.

  50. Maria

    Next, the remaining records are grouped by Location. The speed column is aggregated in two ways: mean gives the average coaster speed for each location, and count gives the number of coasters represented at that location.

  51. Hope

    Then the grouped result is filtered to keep only locations where the count is greater than or equal to 10. Sorting by the mean speed puts the locations in an order that makes the comparison clear.

  52. Maria

    Finally, the result is plotted as a horizontal bar chart using the mean speed. With a title such as Average Coaster Speed by Location and an x-axis label identifying average coaster speed, the chart answers the question directly. Busch Gardens has the highest average coaster speed among the qualifying locations, followed by Cedar Point.

  53. Hope

    So the larger lesson is not just one roller-coaster result. It is a repeatable process: load the data, understand its shape and types, select and clean the relevant columns, investigate missing and duplicate values, explore individual features, compare relationships, and then ask a focused question.

  54. Maria

    And asking that question is what pushes the analysis forward. You may not know every pandas operation at the beginning, but a concrete question helps you identify the filtering, grouping, aggregation, sorting, and plotting steps needed to reach an answer.

  55. Hope

    That gives you a solid foundation for simple data exploration with Python, pandas, matplotlib, and seaborn.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent