Lesson 54 · Real-World Data Analytics
Datetime & pd.cut in Pandas: Earthquake Data Analysis | Python Data Analytics #54
Moving from a slow-moving climate trend to a real sudden environmental hazard. A real USGS-sourced dataset of magnitude five point five and higher…
- CourseReal-World Data Analytics
- Lesson54 of 100
- Video16 min
- FormatJupyter notebook · 30 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- earthquakes_1965_1966.csv preview49.2 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 54: Real Global Earthquake Analysis#
- Video fifty-four of the hundred-video real-world data analytics series, moving from a slow-moving climate trend to a real sudden environmental hazard.
- A real USGS-sourced dataset of magnitude five point five and higher earthquakes, honestly scoped to the first four hundred sixty-one real events, covering January 1965 through June 1966.
- Let's get into it.
This lesson is for learners who want to practise exploring an event catalogue, where each row is a single incident rather than a regular time step. The question is: what did global earthquake activity look like in a defined window, how strong and how deep were the quakes, and where did they cluster?
The data comes from the USGS catalogue of significant earthquakes of magnitude 5.5 and above, scoped honestly to its first 461 events, from January 1965 to June 1966. The columns that matter are Date, Latitude, Longitude, Depth (in kilometres), Magnitude and Magnitude Type. Many measurement-error columns exist but are empty for this early period.
In this lesson you will:
- recognise columns that are entirely empty and decide whether they matter
- parse dates with an explicit format and group events by month
- find the strongest, deepest and shallowest events
- classify depth into categories with
np.select - compare magnitudes across groups and chart the distributions
Prerequisites: you should be comfortable with pandas filtering, groupby and value_counts. Earlier lessons in the series cover these if you need a refresher.
Part 1: A Real Earthquake Catalog#
Loading the catalogue and checking its size tells you how many events you are working with. The code imports pandas, numpy and matplotlib, reads earthquakes_1965_1966.csv and shows .shape. The output is (461, 21): 461 earthquakes described by 21 columns. Remember this is a scoped sample covering about 18 months, so any counts you produce describe this window only, not earthquakes in general.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
quakes = pd.read_csv('earthquakes_1965_1966.csv')
quakes.shape
Part 2: Real Data Preview#
A preview helps you understand each column before you analyse it. The code has two expressions, but Jupyter only displays the last, so the output is quakes.head(5). You can see dates as text in month/day/year order (such as 01/02/1965), coordinates in decimal degrees, Depth in kilometres and Magnitude values like 6.0 and 5.8. Several columns, including Depth Error and Horizontal Error, already show NaN, pandas' marker for missing data.
quakes.columns.tolist()
quakes.head(5)
Part 3: Real Missing Data Check#
Counting missing values shows which columns you can rely on. quakes.isna().sum() counts NaN cells per column. The output shows the core fields (date, time, coordinates, depth, magnitude and IDs) are complete, but eight columns, such as Depth Error, Magnitude Error and Root Mean Square, are missing in all 461 rows. This reflects the early source data, not a processing mistake. When a column is completely empty, you simply leave it out of the analysis rather than trying to fill it.
quakes.isna().sum()
Part 4: Real Duplicate Row Check#
A catalogue can contain the same event twice if it was merged from several feeds, which would inflate counts. quakes.duplicated() flags rows that exactly repeat an earlier row, and .sum() counts them. The output np.int64(0) means no duplicates. For extra assurance in event data, you can also check that the ID column is unique with quakes['ID'].is_unique.
quakes.duplicated().sum()
Part 5: Real Date Parsing#
Dates must be real datetime values before you can sort, filter or group by month. pd.to_datetime converts the text in Date, and format='%m/%d/%Y' tells pandas the exact order: month, day, four-digit year. Giving the format avoids pandas guessing wrongly between day-first and month-first dates. The output confirms the window runs from 2 January 1965 to 15 June 1966.
quakes['date_parsed'] = pd.to_datetime(quakes['Date'], format='%m/%d/%Y')
quakes['date_parsed'].min(), quakes['date_parsed'].max()
Part 6: Real Strongest Earthquake#
The strongest event is usually the headline in any earthquake summary. quakes['Magnitude'].idxmax() returns the row label of the highest magnitude, and .loc fetches that row. The output shows a magnitude 8.7 earthquake on 4 February 1965 at latitude 51.251, longitude 178.715, which is in the Aleutian Islands region near Alaska. If two events tied, idxmax() would return only the first.
strongest = quakes.loc[quakes['Magnitude'].idxmax()]
strongest[['date_parsed', 'Magnitude', 'Latitude', 'Longitude']]
Part 7: Real Average Magnitude#
An average gives a sense of a typical event in the catalogue. quakes['Magnitude'].mean() averages all magnitudes and round(..., 2) keeps two decimals. The output is 6.01. Because this catalogue only includes events of magnitude 5.5 or above, the average is pushed up by design, so it describes significant quakes, not all earthquakes. Magnitude is also logarithmic: each whole step represents a much larger release of energy, so averages should be read with care.
avg_magnitude = round(quakes['Magnitude'].mean(), 2)
avg_magnitude
Part 8: Real Magnitude Distribution Chart#
A histogram shows how values are spread out by grouping them into ranges called bins and counting how many fall into each. ax.hist with bins=20 splits the magnitude range into 20 equal-width bins, and edgecolor='black' outlines each bar so they are easy to tell apart. The chart is saved as magnitude_distribution.png with no inline output. In the image, expect tall bars near 5.5 to 6 and a long thin tail to the right, since strong earthquakes are much rarer than moderate ones.
fig, ax = plt.subplots(figsize=(9, 6))
ax.hist(quakes['Magnitude'], bins=20, color='firebrick', edgecolor='black')
ax.set_xlabel('Real Magnitude')
ax.set_ylabel('Real Number of Earthquakes')
ax.set_title('Real Earthquake Magnitude Distribution, Jan 1965-Jun 1966')
plt.tight_layout()
plt.savefig('magnitude_distribution.png', dpi=100)
plt.close()
Part 9: Real Average Depth#
Depth affects how much shaking reaches the surface, so it is a key measure alongside magnitude. quakes['Depth'].mean() gives the average depth in kilometres, rounded to one decimal. The output is 65.2 km. A few very deep events can pull an average up, so it is worth checking the median as well, which you can do with .median().
avg_depth = round(quakes['Depth'].mean(), 1)
avg_depth
Part 10: Real Deepest Earthquake#
Finding the deepest event shows the range of depths in the catalogue. idxmax() on Depth returns the row label of the deepest earthquake, and .loc retrieves its date, depth and magnitude. The output shows a quake on 9 December 1965 at 645 km below the surface, with magnitude 6.2. Very deep earthquakes like this happen where one tectonic plate dives deep beneath another.
deepest = quakes.loc[quakes['Depth'].idxmax()]
deepest[['date_parsed', 'Depth', 'Magnitude']]
Part 11: Real Shallowest Earthquake#
The shallowest event is the other end of the depth range. idxmin() on Depth returns the first row with the smallest depth. The output shows an event on 4 February 1965 at 10 km with magnitude 6.1. Note that 10 km is a common default depth assigned when the true depth could not be measured precisely, so many events may share this value and idxmin() simply returns the first of them.
shallowest = quakes.loc[quakes['Depth'].idxmin()]
shallowest[['date_parsed', 'Depth', 'Magnitude']]
Part 12: Real Depth vs Magnitude Chart#
A scatter chart lets you check whether deeper earthquakes tend to be stronger or weaker. ax.scatter plots Depth on the x-axis and Magnitude on the y-axis, and alpha=0.5 makes points semi-transparent so overlapping dots show up as darker areas. The chart is saved as depth_vs_magnitude.png with no inline output. In the image, look for a dense cluster at shallow depths and whether the spread of magnitudes changes as depth increases.
fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(quakes['Depth'], quakes['Magnitude'], alpha=0.5, color='darkorange')
ax.set_xlabel('Real Depth, Kilometers')
ax.set_ylabel('Real Magnitude')
ax.set_title('Real Earthquake Depth vs Magnitude')
plt.tight_layout()
plt.savefig('depth_vs_magnitude.png', dpi=100)
plt.close()
Part 13: Real Major Earthquake Count#
Counting major earthquakes, commonly defined as magnitude 7 or above, focuses attention on the most damaging events. (quakes['Magnitude'] >= 7) gives True or False for each row, and .sum() counts the Trues. The output is 20, about 4% of the 461 events in this window. Always state your threshold when you report a count like this, since definitions vary.
major_quakes = (quakes['Magnitude'] >= 7).sum()
major_quakes
Part 14: Real Strong Earthquake Count#
Repeating the count at a lower threshold shows how quickly numbers rise as you include smaller quakes. The code counts events with Magnitude >= 6 the same way. The output is 200, ten times the number at magnitude 7 or above. This pattern, many more moderate quakes than large ones, is a well-known feature of earthquake catalogues and matches the shape you would see in the histogram.
strong_quakes = (quakes['Magnitude'] >= 6).sum()
strong_quakes
Part 15: Real Earthquakes by Month#
Grouping by month shows whether activity was steady or bunched together. .dt.to_period('M') converts each date into a year-month period such as 1965-02, and groupby('month').size() counts events per month. Sorting in descending order and taking .head(3) gives the busiest months: February 1965 with 54, March 1965 with 38 and August 1965 with 34. A spike right after a very large quake often reflects aftershocks, which fits the 8.7 event in February.
quakes['month'] = quakes['date_parsed'].dt.to_period('M')
monthly_counts = quakes.groupby('month').size()
monthly_counts.sort_values(ascending=False).head(3)
Part 16: Real Monthly Activity Chart#
A bar per month gives the full timeline of activity, not just the top three. The code plots monthly_counts with kind='bar' on a wide figure so all 18 month labels fit. It is saved as monthly_activity.png with no inline output. In the image, look for the tall February 1965 bar standing out from the rest and whether activity drops back to a steady baseline afterwards.
fig, ax = plt.subplots(figsize=(11, 5))
monthly_counts.plot(kind='bar', ax=ax, color='steelblue')
ax.set_xlabel('Real Year-Month')
ax.set_ylabel('Real Number of Earthquakes')
ax.set_title('Real Earthquake Activity by Month, Jan 1965-Jun 1966')
plt.tight_layout()
plt.savefig('monthly_activity.png', dpi=100)
plt.close()
Part 17: Real Hemisphere Split#
Splitting by hemisphere is a simple first look at geography. Positive latitudes are north of the equator and negative ones are south, so the code counts Latitude >= 0 and Latitude < 0 separately. The output (275, 186) shows 275 events in the Northern Hemisphere and 186 in the Southern. Note that an event exactly on the equator would be counted as northern here because of the >=.
northern = (quakes['Latitude'] >= 0).sum()
southern = (quakes['Latitude'] < 0).sum()
northern, southern
Part 18: Real Hemisphere Chart#
A two-bar chart makes the hemisphere split easy to compare at a glance. ax.bar takes a list of labels and a list of the two counts, with a different colour for each bar. The chart is saved as hemisphere_split.png and is not displayed inline. In the image, the northern bar should be noticeably taller, matching the 275 versus 186 counts.
fig, ax = plt.subplots(figsize=(7, 6))
ax.bar(['Real Northern', 'Real Southern'], [northern, southern], color=['steelblue', 'firebrick'])
ax.set_ylabel('Real Number of Earthquakes')
ax.set_title('Real Earthquakes by Hemisphere, Jan 1965-Jun 1966')
plt.tight_layout()
plt.savefig('hemisphere_split.png', dpi=100)
plt.close()
Part 19: Real Magnitude Type Check#
Magnitudes can be measured on different scales, and mixing them would make comparisons unreliable. value_counts() on Magnitude Type counts each scale used. The output shows MW for all 461 events, so every value is on the moment magnitude scale, the standard modern measure of earthquake size. That means the averages and thresholds in this lesson compare like with like.
quakes['Magnitude Type'].value_counts()
Part 20: Real Depth Category Classification#
Raw depth numbers are hard to interpret, so seismologists group them into standard bands: shallow (under 70 km), intermediate (70 to 300 km) and deep (300 km or more). np.select checks a list of conditions in order and assigns the matching label from a second list, with default used if none match. The output shows 379 shallow, 62 intermediate and 20 deep events. Make sure your conditions do not overlap, because np.select uses the first one that is True.
conditions = [quakes['Depth'] < 70, (quakes['Depth'] >= 70) & (quakes['Depth'] < 300), quakes['Depth'] >= 300]
quakes['depth_category'] = np.select(conditions, ['shallow', 'intermediate', 'deep'], default='shallow')
quakes['depth_category'].value_counts()
Part 21: Real Depth Category Chart#
A bar chart of the depth categories shows how unevenly earthquakes are spread by depth. The code runs value_counts() on depth_category and plots it with kind='bar', keeping the labels upright with plt.xticks(rotation=0). It is saved as depth_categories.png with no inline output. In the image, expect one dominant shallow bar, with intermediate and deep much smaller, and note that value_counts() orders the bars from largest to smallest.
fig, ax = plt.subplots(figsize=(7, 6))
quakes['depth_category'].value_counts().plot(kind='bar', ax=ax, color='seagreen')
ax.set_xlabel('Real Depth Category')
ax.set_ylabel('Real Number of Earthquakes')
ax.set_title('Real Earthquakes by Depth Category')
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig('depth_categories.png', dpi=100)
plt.close()
Part 22: Real Shallow Earthquake Percentage#
A percentage is easier to communicate than a raw count. (quakes['depth_category'] == 'shallow') gives True or False for each row, and .mean() on True and False values gives the share that are True, because True counts as 1 and False as 0. Multiplying by 100 and rounding gives the output 82.2, so 82.2% of events were shallow. This is a common pandas pattern worth remembering.
shallow_pct = round((quakes['depth_category'] == 'shallow').mean() * 100, 1)
shallow_pct
Part 23: Real Top Five Strongest Earthquakes#
Listing the top events gives context that a single maximum cannot. quakes.nlargest(5, 'Magnitude') returns the five rows with the highest magnitude, and the column list keeps the date, magnitude, depth and location. The output runs from 8.7 on 4 February 1965 down to 7.6 on 30 March 1965, with depths from 20 to 120 km. Notice that three of the five sit at latitudes around 50 to 53 degrees north, and the 30 March event is close to the location of the 8.7 quake.
top5 = quakes.nlargest(5, 'Magnitude')[['date_parsed', 'Magnitude', 'Depth', 'Latitude', 'Longitude']]
top5
Part 24: Real Average Magnitude by Depth Category#
Comparing the average magnitude across depth categories tests whether deeper quakes in this sample tend to be stronger. groupby('depth_category')['Magnitude'].mean() averages each group, rounded to two decimals. The output shows deep 6.11, intermediate 6.02 and shallow 6.01. The differences are small, and the deep group only has 20 events, so this is not strong evidence of a real difference.
magnitude_by_depth = quakes.groupby('depth_category')['Magnitude'].mean().round(2)
magnitude_by_depth
Part 25: Real Sanity Check, Honest Scope#
This check confirms that the data matches its stated scope of magnitude 5.5 and above. (quakes['Magnitude'] >= 5.5) creates a True or False value per row, and .all() returns True only if every row passes. The output np.True_ (numpy's True) confirms that every event meets the threshold. Testing documented rules like this protects you from building conclusions on data that does not match its description.
(quakes['Magnitude'] >= 5.5).all()
Part 26: Saving the Real Enriched Dataset#
Saving the enriched catalogue keeps your parsed dates, months and depth categories for later analysis. to_csv(..., index=False) writes the file without the index, and the code reloads it and compares shapes. The output is True, so the rows and columns survived. When you reload, date_parsed will be text again and month will no longer be a period type, so convert them back if you need date features.
quakes.to_csv('earthquakes_enriched.csv', index=False)
reloaded = pd.read_csv('earthquakes_enriched.csv')
reloaded.shape == quakes.shape
Part 27: Real Sanity Check, Row Count#
A quick count confirms that no rows were added or dropped while you created new columns. len(quakes) == 461 compares the current length with the original. The output is True, so the full set of events is still present. This kind of check is especially important after merges, which can quietly duplicate rows.
len(quakes) == 461
Part 28: Real Sanity Check, No Missing Coordinates#
Maps, depth categories and magnitude counts all depend on four columns being complete. The code selects Latitude, Longitude, Magnitude and Depth, counts NaN per column with .isna().sum(), then adds those counts together with a second .sum(). Comparing the total with 0 gives the output np.True_, so none of these essential fields has any gaps. The double .sum() is a handy way to count missing values across several columns at once.
quakes[['Latitude', 'Longitude', 'Magnitude', 'Depth']].isna().sum().sum() == 0
Part 29: Real Top Finding Print#
The headline finding becomes one clear sentence for a report. The f-string pulls the date, magnitude and coordinates from the strongest row, using .date() to drop the time part. The output reads that the strongest earthquake struck on 1965-02-04 at magnitude 8.7, near latitude 51.251, longitude 178.715. Building text from variables means the sentence stays correct if the data is extended.
print(f'The real strongest earthquake in this honest window struck on {strongest["date_parsed"].date()} at magnitude {strongest["Magnitude"]}, near latitude {strongest["Latitude"]}, longitude {strongest["Longitude"]}.')
Part 30: Real Recap Print#
The recap summarises the catalogue in a single sentence. The f-string inserts len(quakes), major_quakes, shallow_pct, avg_magnitude and avg_depth. The output reports 461 earthquakes, 20 of magnitude 7 or higher, 82.2% shallow, and an average magnitude of 6.01 at a depth of 65.2 km. When you share findings like this, add the time window and the magnitude 5.5 cut-off so readers know the scope.
print(f'Across {len(quakes)} real tracked earthquakes, {major_quakes} were magnitude seven or higher, {shallow_pct} percent were shallow, and the real average tracked earthquake struck at magnitude {avg_magnitude} and depth {avg_depth} kilometers.')
Wrap-Up: What You Learned#
- This real lesson honestly scoped a real fetch-limited pull from the USGS significant-earthquakes catalog down to its real first four hundred sixty-one events, January 1965 through June 1966, rather than presenting a partial pull as the full population.
- The real strongest tracked earthquake struck at magnitude 8.7 in February 1965 near the Rat Islands off Alaska, and shallow earthquakes genuinely dominated this real window.
- Real uncertainty columns like depth error were honestly all missing for this early ISCGEM-sourced era, a real limitation of the source data rather than a processing mistake.
- Classifying earthquakes into real shallow, intermediate, and deep categories using real standard seismology thresholds turned a raw depth number into something genuinely interpretable.
- Next video: a real global forest and land-cover change dataset, continuing this domain's look at real environmental hazards and change.
Practice on your own
- Compare the median depth with the 65.2 km mean using
quakes['Depth'].median(), and count how many events sit at exactly 10 km. - Filter to the days just after the 8.7 event (4 to 28 February 1965) and count how many events fell within about 5 degrees of its latitude and longitude, a rough check for aftershocks.
- Build a crosstab of
depth_categoryagainst hemisphere withpd.crosstabto see whether deep earthquakes are more common in one hemisphere.
The next lesson moves on to a global forest and land-cover change dataset, continuing the domain's look at environmental change. Watch the video walkthrough of this lesson to see each step explained in action.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



