Lesson 51 · Real-World Data Analytics
Weather Data Analysis in Python: Daily Normals & Records (NYC) | Python Data Analytics #51
And the start of Domain 6, real Climate and Environment analytics. A real FiveThirtyEight dataset of three hundred sixty-five real daily New York City…
- CourseReal-World Data Analytics
- Lesson51 of 100
- Video18 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.
- nyc_weather_history.csv preview20.1 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 51: Real NYC Weather History Analysis#
- Video fifty-one of the hundred-video real-world data analytics series, and the start of Domain 6, real Climate and Environment analytics.
- A real FiveThirtyEight dataset of three hundred sixty-five real daily New York City weather records, each one measured against its real historical average and real all-time record dating back to 1880.
- Let's get into it.
This lesson is for learners who want to practise a complete, small analysis on real environmental data before tackling bigger climate datasets. The business question is simple but useful: how did one year of New York City weather compare with what history says is normal, and where were the extremes?
The dataset comes from FiveThirtyEight and holds one row per day from July 2014 to June 2015. For each day you get the actual mean, minimum and maximum temperature, the historical average minimum and maximum, the all-time record low and high (with the year each record was set), plus actual, average and record precipitation in inches.
In this lesson you will:
- check a fresh dataset for missing values and duplicates
- parse text dates and extract the month
- find extreme days with
idxmax()andidxmin() - compare actual readings against historical averages and records
- summarise temperature and rainfall by month and chart the results
Prerequisites: you should be comfortable loading a CSV with pandas, filtering with boolean masks and using groupby. If any of these feel new, see the earlier lessons in the series first.
Part 1: A Real Year of NYC Weather#
Every analysis starts by loading the data and confirming its size, because the shape tells you whether the file matches what you expect. The code imports pandas, numpy and matplotlib, reads nyc_weather_history.csv with pd.read_csv, and shows .shape, which returns (rows, columns). The output is (365, 13): exactly one year of daily records with 13 columns. If you ever see 364 or 366 rows here, check for a missing day or a leap year before going further.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
weather = pd.read_csv('nyc_weather_history.csv')
weather.shape
Part 2: Real Data Preview#
Before calculating anything, look at the raw rows so you understand what each column means and how values are stored. The code has two expressions, weather.columns.tolist() and weather.head(5), but Jupyter only displays the last one, so the output shows the first five rows. You can see dates stored as text like 2014-7-1, temperatures in whole degrees Fahrenheit, record years such as 1943 and 1901, and precipitation in inches. Notice the year starts on 1 July 2014, not 1 January.
weather.columns.tolist()
weather.head(5)
Part 3: Real Missing Data Check#
Missing values can quietly break sums, averages and comparisons, so you check for them early. weather.isna() marks every empty cell as True, and .sum() counts the Trues in each column, because True counts as 1. The output shows 0 for all 13 columns, so this dataset is complete and needs no filling or dropping. Tip: run this check on every new dataset, even ones from reputable sources, because a single gap can shift a monthly average.
weather.isna().sum()
Part 4: Real Duplicate Row Check#
Duplicate rows would double-count days and inflate totals such as yearly rainfall. weather.duplicated() returns True for any row that is an exact copy of an earlier row, and .sum() counts them. The output is np.int64(0), which simply means zero duplicates stored as a numpy integer. With no missing data and no duplicates, you can trust each row as one unique day. Remember that duplicated() only catches exact copies; two rows for the same date with different values would need a check on the date column alone.
weather.duplicated().sum()
Part 5: Real Date Parsing#
The date column arrives as text, which means pandas cannot sort it by time, extract months or plot it properly on a time axis. pd.to_datetime converts the text into real datetime values, and .dt.month pulls out the month number (1 to 12) into a new month column. The output shows the first three rows now reading 2014-07-01, 2014-07-02 and 2014-07-03, each with month 7. This new column is what makes the monthly summaries later in the lesson possible.
weather['date'] = pd.to_datetime(weather['date'])
weather['month'] = weather['date'].dt.month
weather[['date', 'month']].head(3)
Part 6: Real Hottest Day#
Extreme days are often the headline in weather reporting, so finding the hottest day is a natural first question. weather['actual_max_temp'].idxmax() returns the row label of the highest maximum temperature, and weather.loc[...] fetches that whole row. The output shows the hottest day was 2 September 2014 at 92 degrees F. Note that idxmax() returns only the first match if several days tie, so check with a filter if ties matter to your question.
hottest_day = weather.loc[weather['actual_max_temp'].idxmax()]
hottest_day[['date', 'actual_max_temp']]
Part 7: Real Coldest Day#
The coldest day is the mirror question to the hottest. This time the code uses idxmin() on actual_min_temp, the overnight low, which is the right column for measuring the coldest conditions. weather.loc[...] returns that full row, and the output shows 20 February 2015 with a low of just 2 degrees F, at row label 234. Keep the coldest_day variable in mind: it is reused in the final summary print to report this finding.
coldest_day = weather.loc[weather['actual_min_temp'].idxmin()]
coldest_day[['date', 'actual_min_temp']]
Part 8: Real Record High Days#
Records are what make a weather year memorable, so the next step checks whether any day matched or beat its all-time record high. The comparison actual_max_temp >= record_max_temp produces True or False for each day, and .sum() counts the Trues. The output is 0: no day in this year reached its record high. Using >= rather than > is deliberate, because it also catches days that tied a record.
record_highs = (weather['actual_max_temp'] >= weather['record_max_temp']).sum()
record_highs
Part 9: Real Record Low Days#
Now the same idea for cold records, but this time the code keeps the matching rows instead of just counting them, so you can see the details. The filter actual_min_temp <= record_min_temp selects any day at or below its record low, and the column list shows the date, actual low, record low and record year. The output has one row: 20 February 2015 hit 2 degrees F, equal to the record, and the record year is now listed as 2015. In other words, the coldest day of the year tied the all-time low for that date.
record_low_rows = weather[weather['actual_min_temp'] <= weather['record_min_temp']]
record_low_rows[['date', 'actual_min_temp', 'record_min_temp', 'record_min_temp_year']]
Part 10: Real Actual vs Average Max Temp Chart#
A line chart lets you see the whole year at once and spot when actual temperatures drifted away from normal. The code creates a figure with plt.subplots(figsize=(11, 6)), then draws two lines with ax.plot: daily actual maximum in red and the historical average maximum in blue, thicker so it reads as the baseline. The chart is saved to actual_vs_average_temp.png and closed, so nothing is displayed in the notebook. When you open the image, look for the smooth seasonal curve of the average and the spiky actual line crossing above and below it.
fig, ax = plt.subplots(figsize=(11, 6))
ax.plot(weather['date'], weather['actual_max_temp'], label='Real Actual Max Temp', color='firebrick', linewidth=0.8)
ax.plot(weather['date'], weather['average_max_temp'], label='Real Historical Average Max Temp', color='steelblue', linewidth=1.5)
ax.set_ylabel('Real Temperature, Degrees F')
ax.set_title('Real NYC Daily Max Temp vs Real Historical Average, 2014-2015')
ax.legend()
plt.tight_layout()
plt.savefig('actual_vs_average_temp.png', dpi=100)
plt.close()
Part 11: Real Days Above vs Below Average#
To judge whether the year ran warm or cold, you need a single deviation number per day. The code estimates the normal daily mean as the average of average_min_temp and average_max_temp, then subtracts it from actual_mean_temp to create temp_vs_avg. Counting values above and below zero gives the output (176, 182): 176 warmer-than-normal days and 182 cooler ones. The remaining 7 days sat exactly on the estimated norm. Taking the midpoint of min and max is a common shortcut, not an official average, so treat it as an approximation.
weather['temp_vs_avg'] = weather['actual_mean_temp'] - (weather['average_min_temp'] + weather['average_max_temp']) / 2
(weather['temp_vs_avg'] > 0).sum(), (weather['temp_vs_avg'] < 0).sum()
Part 12: Real Average Deviation from Norm#
Counting warm and cool days tells you how often the year deviated, but not by how much. Taking .mean() of temp_vs_avg gives the average gap in degrees, and round(..., 2) keeps two decimal places. The output is -0.31, meaning the year ran about a third of a degree Fahrenheit cooler than normal on average. That is very close to zero, so overall this was a typical year, even though individual days swung widely.
avg_deviation = round(weather['temp_vs_avg'].mean(), 2)
avg_deviation
Part 13: Real Monthly Average Temperature#
Monthly averages turn 365 noisy daily readings into twelve numbers you can compare and explain. groupby('month') splits the rows by month, ['actual_mean_temp'].mean() averages each group, and .round(1) tidies the result. The output runs from 24.2 degrees F in February to 76.3 degrees F in July, with August close behind at 74.7. Note that the index is the month number, sorted 1 to 12, even though the data itself starts in July.
monthly_avg_temp = weather.groupby('month')['actual_mean_temp'].mean().round(1)
monthly_avg_temp
Part 14: Real Monthly Temperature Chart#
A bar chart of the monthly averages makes the seasonal cycle obvious at a glance. The code calls .plot(kind='bar') directly on the monthly_avg_temp Series, draws it onto the axes created with plt.subplots, and plt.xticks(rotation=0) keeps the month numbers upright. The figure is saved as monthly_avg_temp.png rather than shown. In the image, look for the low bars in January and February rising to a peak in July, then falling through the autumn.
fig, ax = plt.subplots(figsize=(9, 6))
monthly_avg_temp.plot(kind='bar', ax=ax, color='darkorange')
ax.set_xlabel('Real Calendar Month')
ax.set_ylabel('Real Average Mean Temp, Degrees F')
ax.set_title('Real NYC Average Monthly Temperature, 2014-2015')
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig('monthly_avg_temp.png', dpi=100)
plt.close()
Part 15: Real Total Precipitation#
Rainfall is the second half of the weather story. The code adds up actual_precipitation and average_precipitation across all 365 days with .sum() and rounds each to two decimals. The output (46.05, 49.94) shows the year received 46.05 inches of precipitation against a historical norm of 49.94 inches. Summing daily averages to get an annual norm works here because every day of the year is present, which you confirmed earlier.
total_actual_precip = round(weather['actual_precipitation'].sum(), 2)
total_average_precip = round(weather['average_precipitation'].sum(), 2)
total_actual_precip, total_average_precip
Part 16: Real Precipitation Deviation#
A single difference makes the rainfall comparison easy to report. The code subtracts the historical total from the actual total and rounds to two decimals. The output is -3.89, so the year was 3.89 inches drier than normal, roughly 8% below the norm of 49.94 inches. The sign matters: a negative value means below normal, and the final recap print later turns that sign into the words above or below.
precip_deviation = round(total_actual_precip - total_average_precip, 2)
precip_deviation
Part 17: Real Heavy Rain Days#
Total rainfall can hide how it arrived: a few downpours or steady drizzle. Here a heavy rain day is defined as more than 1 inch, and (weather['actual_precipitation'] > 1).sum() counts how many days crossed that line. The output is 14 heavy rain days. The 1-inch threshold is a choice, not a standard, so state it clearly whenever you report this kind of figure.
heavy_rain_days = (weather['actual_precipitation'] > 1).sum()
heavy_rain_days
Part 18: Real Daily Precipitation Chart#
A daily bar chart shows when the rain fell across the year and makes the heavy days stand out. The code uses ax.bar with dates on the x-axis and width=1.0 so each bar fills one full day without gaps. The figure is saved to daily_precipitation.png and closed, so there is no inline output. In the image, look for the tall spikes, which are the 14 heavy rain days, and for any dry spells with very few bars.
fig, ax = plt.subplots(figsize=(11, 5))
ax.bar(weather['date'], weather['actual_precipitation'], color='teal', width=1.0)
ax.set_ylabel('Real Precipitation, Inches')
ax.set_title('Real NYC Daily Precipitation, 2014-2015')
plt.tight_layout()
plt.savefig('daily_precipitation.png', dpi=100)
plt.close()
Part 19: Real Days Below Freezing#
Freezing days matter for heating demand, road gritting and transport planning, so they are a useful operational measure. The code compares each day's actual_min_temp with 32 degrees F, the freezing point of water, and counts the Trues with .sum(). The output is 82, meaning the temperature dropped below freezing on 82 days, a bit over a fifth of the year. Using the minimum temperature is correct here, since a day counts as freezing if it went below 32 at any point.
freezing_days = (weather['actual_min_temp'] < 32).sum()
freezing_days
Part 20: Real Freezing Days by Month#
Knowing how many freezing days there were is helpful; knowing when they fell is more actionable. The code filters to rows below 32 degrees F, then groupby('month').size() counts rows in each month. The output shows January 24, February 27, March 16, November 7 and December 8, which add up to the 82 found earlier. Months with no freezing days simply do not appear, because .size() only reports groups that exist after filtering.
freezing_by_month = weather[weather['actual_min_temp'] < 32].groupby('month').size()
freezing_by_month
Part 21: Real Freezing Days Chart#
Turning the monthly freezing counts into a bar chart makes the shape of winter easy to see. The code plots freezing_by_month with kind='bar' in navy, labels both axes, keeps the month numbers upright and saves the result to freezing_days_by_month.png. Nothing is displayed inline. When you look at the image, notice that only five bars appear, with February tallest, and remember that missing months mean zero freezing days, not missing data.
fig, ax = plt.subplots(figsize=(9, 6))
freezing_by_month.plot(kind='bar', ax=ax, color='navy')
ax.set_xlabel('Real Calendar Month')
ax.set_ylabel('Real Number of Below-Freezing Days')
ax.set_title('Real NYC Below-Freezing Days by Month, 2014-2015')
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig('freezing_days_by_month.png', dpi=100)
plt.close()
Part 22: Real Hottest Month#
The hottest month gives you a quick summary of peak summer. monthly_avg_temp.idxmax() returns the index label (the month number) of the highest value, and .max() returns the value itself. The output (7, 76.3) shows July was the hottest month with an average mean temperature of 76.3 degrees F. The np.int32 and np.float64 labels in the output are just numpy number types and do not change the values.
hottest_month = monthly_avg_temp.idxmax()
hottest_month, monthly_avg_temp.max()
Part 23: Real Coldest Month#
The coldest month is the matching winter summary. idxmin() returns the month number with the lowest average and .min() returns that average. The output (2, 24.2) shows February was the coldest month at 24.2 degrees F, which fits with it also having the most freezing days (27) and containing the coldest single day. Cross-checking findings like this is a good habit, because consistent results build confidence in your analysis.
coldest_month = monthly_avg_temp.idxmin()
coldest_month, monthly_avg_temp.min()
Part 24: Real Precipitation Record Days#
Just as with temperature, you can check whether any day matched or beat its all-time rainfall record. The code compares actual_precipitation with record_precipitation using >= and counts the Trues. The output is 4, so four days equalled or set new precipitation records for their date. That is notable in a year that was drier overall, and shows why totals and extremes should be reported together.
precip_records = (weather['actual_precipitation'] >= weather['record_precipitation']).sum()
precip_records
Part 25: Real Enriched Weather Dataset#
Adding a simple flag column makes the dataset easier for others to filter and reuse. weather['temp_vs_avg'] > 0 creates a True or False column called ran_warmer, and .sum() counts the warm days. The output is 176, matching the earlier count of above-average days, which confirms the flag was built correctly. Boolean flag columns like this are handy in later tools such as spreadsheets or dashboards.
weather['ran_warmer'] = weather['temp_vs_avg'] > 0
weather['ran_warmer'].sum()
Part 26: Saving the Real Enriched Dataset#
Saving your enriched data means the next analysis can start from the cleaned version rather than repeating every step. to_csv('nyc_weather_enriched.csv', index=False) writes the file without the pandas row index, and the code then reloads it with pd.read_csv and compares shapes. The output is True, so the saved file has the same rows and columns as the data in memory. Note that the reloaded date column will be text again until you parse it with pd.to_datetime.
weather.to_csv('nyc_weather_enriched.csv', index=False)
reloaded = pd.read_csv('nyc_weather_enriched.csv')
reloaded.shape == weather.shape
Part 27: Real Sanity Check, Full Year#
Sanity checks are short tests that confirm your data still matches your expectations after all the transformations. len(weather) == 365 checks that no rows were lost or added along the way. The output is True, so the dataset still covers a full year of days. Putting checks like this near the end of a notebook catches accidental filtering or merging mistakes before you share results.
len(weather) == 365
Part 28: Real Sanity Check, Twelve Months#
A second check confirms that every calendar month is represented, which matters because the monthly summaries assume twelve groups. weather['month'].nunique() counts the distinct month numbers, and the comparison with 12 returns True or False. The output is True, so all twelve months are present. If this ever returned False, the monthly charts and the hottest and coldest month results would be incomplete.
weather['month'].nunique() == 12
Part 29: Real Top Finding Print#
Analysis is only useful once it is communicated, so the notebook turns the most striking finding into a plain sentence. The f-string pulls the date and minimum temperature from the coldest_day row, and .date() drops the time part from the timestamp. The output reads that the coldest day was 2015-02-20 at 2 degrees, tying the all-time record low for that date. Building sentences from variables rather than typing numbers by hand keeps your text correct if the data changes.
print(f'The real coldest day was {coldest_day["date"].date()} at {coldest_day["actual_min_temp"]} degrees, which genuinely tied the real all-time record low for that date.')
Part 30: Real Recap Print#
The final recap combines several results into one summary sentence suitable for a report or slide. The f-string uses len(weather), freezing_days, abs(precip_deviation) to drop the minus sign, and an inline if expression to choose the word above or below. The output says that across 365 days, 82 were below freezing, precipitation ran 3.89 inches below the norm and the year averaged -0.31 degrees off its baseline. Tip: check that the wording still reads well if the sign of a value flips.
print(f'Across {len(weather)} real days of New York City weather, {freezing_days} were below freezing, real precipitation ran {abs(precip_deviation)} inches {"above" if precip_deviation > 0 else "below"} the historical norm, and this real year averaged {avg_deviation} degrees off its real historical baseline.')
Wrap-Up: What You Learned#
- This real lesson opened Domain 6, Climate and Environment, with a real FiveThirtyEight dataset of three hundred sixty-five real daily New York City weather records, zero missing or duplicate values.
- This real year ran almost exactly on its real historical average overall, but individual real days still swung to a real tied all-time record low.
- Real precipitation came in slightly below the real historical norm for the year, even with fourteen real days of heavy rain along the way.
- Real winter months carried the heaviest real share of below-freezing days, while real summer months ran consistently above the real historical baseline.
- Next video: a real global CO2 emissions dataset, moving from local weather to a real worldwide climate perspective.
Practice on your own
- Repeat the monthly summary for rainfall: group by
month, sumactual_precipitationandaverage_precipitation, and find which month was furthest above or below its norm. - Count how many days came within 5 degrees F of their record high (
record_max_temp - actual_max_temp <= 5) and list them with their dates and record years. - Use
temp_vs_avgto find the five warmest and five coolest days relative to normal withnlargest(5)andnsmallest(5), then check which months they fall in.
The next lesson moves from local weather to a global CO2 emissions dataset, giving you a worldwide view of climate data. Watch the video walkthrough for this lesson if you want 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.



