Task 3P: pandas vs SQL - Analysis of NYC Flights 2013¶

Name: Thi Thu Suong Ngo

Student Number: 224757434

Email: s224757434@deakin.edu.au

Unit: SIT731 Data Wrangling (Postgraduate Student)

Introduction¶

This report is a detailed analysis of the NYC Flights 2013 dataset, which includes data on 336,776 flights that have departed from three New York airports (EWR, JFK and LGA) in 2013. It contains the information regarding flights, airlines, airports, planes, and weather conditions.

The main goal of this assignment is to show the mastery of data manipulation by comparing the way of analyzing data using SQL and pandas. In each of the presented SQL queries, I will introduce a corresponding solution with the help of pandas and ensure that the two methods give the same results. This exercise emphasizes the flexibility of pandas as an effective data manipulation tool which is capable of recreating the sophisticated SQL operations in Python.

The analysis technique is designed in such a way that it supports different data operations such as filtering, grouping, aggregating, sorting, and joining between two or more tables. This illustrates the basic and the advanced functions of pandas in data wrangling activities.

Setup and Data Loading¶

I first load up the required libraries and make a connection with a SQLite database, and then loading all CSVs into pandas DataFrames and SQL database to compare them.

Q1. Connect with a new SQLite database¶

In [ ]:
# Import required libraries
import pandas as pd
import sqlite3
import warnings
warnings.filterwarnings('ignore')

# Establish connection with SQLite database
conn = sqlite3.connect('nycflights13.db')
print("Database connection established successfully.")
Database connection established successfully.

Q2. Load CSV files into pandas DataFrames and export to SQLite database¶

In [3]:
# Read all CSV files (they are gzipped, pandas handles this automatically)
flights = pd.read_csv('nycflights13_flights.csv.gz', comment='#')
airlines = pd.read_csv('nycflights13_airlines.csv.gz', comment='#')
airports = pd.read_csv('nycflights13_airports.csv.gz', comment='#')
planes = pd.read_csv('nycflights13_planes.csv.gz', comment='#')
weather = pd.read_csv('nycflights13_weather.csv.gz', comment='#')

# Export DataFrames to SQLite database
flights.to_sql('flights', conn, if_exists='replace', index=False)
airlines.to_sql('airlines', conn, if_exists='replace', index=False)
airports.to_sql('airports', conn, if_exists='replace', index=False)
planes.to_sql('planes', conn, if_exists='replace', index=False)
weather.to_sql('weather', conn, if_exists='replace', index=False)

print(f"Data loaded successfully:")
print(f"  - Flights: {len(flights):,} rows")
print(f"  - Airlines: {len(airlines):,} rows")
print(f"  - Airports: {len(airports):,} rows")
print(f"  - Planes: {len(planes):,} rows")
print(f"  - Weather: {len(weather):,} rows")
Data loaded successfully:
  - Flights: 336,776 rows
  - Airlines: 16 rows
  - Airports: 1,458 rows
  - Planes: 3,322 rows
  - Weather: 26,130 rows

The data has been managed to load into memory and exported to SQLite database, now I am able to analyse all five tables.

Here, I run every SQL query with pandas and keep the results with the same output by testing with the help of the frame-equal assertion of the pandas testing pd.testing.assert_frame_equal().

Q3: Using pandas Equivalents SQL Queries¶

Query 1¶

This query gets all the different engine types in the planes table. It demonstrates the usage of various types of engines among all aircrafts of the dataset.

In [4]:
# SQL approach
task1_sql = pd.read_sql_query("""
SELECT DISTINCT engine FROM planes
""", conn)

# pandas approach
task1_my = planes[['engine']].drop_duplicates().reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task1_sql, task1_my)
print("Query 1 verification: PASSED")
print(f"Found {len(task1_my)} unique engine types")
Query 1 verification: PASSED
Found 6 unique engine types

Query 2¶

This query retrieves all unique combinations of aircraft type and engine type. It shows which engine types are paired with which aircraft types in the fleet.

In [7]:
# SQL approach
task2_sql = pd.read_sql_query("""
SELECT DISTINCT type, engine FROM planes
""", conn)

# pandas approach
task2_my = planes[['type', 'engine']].drop_duplicates().reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task2_sql, task2_my)
print("Query 2 verification: PASSED")
print(f"Found {len(task2_my)} unique type-engine combinations")
Query 2 verification: PASSED
Found 7 unique type-engine combinations

Query 3¶

This query will extract all the distinctive engine types in the planes table. It indicates the usage of various engine types in the entire aircrafts of the dataset.

In [8]:
# SQL approach
task3_sql = pd.read_sql_query("""
SELECT COUNT(*), engine FROM planes GROUP BY engine
""", conn)

# pandas approach
task3_my = planes.groupby('engine').size().reset_index(name='COUNT(*)')
task3_my = task3_my[['COUNT(*)', 'engine']]  

# Verify results match
pd.testing.assert_frame_equal(task3_sql, task3_my)
print("Query 3 verification: PASSED")
print(f"Engine type distribution calculated for {len(task3_my)} engine types")
Query 3 verification: PASSED
Engine type distribution calculated for 6 engine types

Query 4¶

This query quantifies the number of planes by the engine type. It gives a summarized picture of the representation of aircraft of various engine types within the dataset.

In [10]:
# SQL approach
task4_sql = pd.read_sql_query("""
SELECT COUNT(*), engine, type FROM planes
GROUP BY engine, type
""", conn)

# pandas approach
task4_my = planes.groupby(['engine', 'type']).size().reset_index(name='COUNT(*)')
task4_my = task4_my[['COUNT(*)', 'engine', 'type']]  

# Verify results match
pd.testing.assert_frame_equal(task4_sql, task4_my)
print("Query 4 verification: PASSED")
print(f"Found {len(task4_my)} unique engine-type combinations with counts")
Query 4 verification: PASSED
Found 7 unique engine-type combinations with counts

Query 5¶

This query computes aggregate statistics of the manufacturing year of airplanes in terms of engine type and manufacturer. It displays the lowest, mean and highest manufacturing year per engine-manufacturer combination, which indicates the distribution of the age of the various types of aircrafts.

In [ ]:
# SQL approach
task5_sql = pd.read_sql_query("""
SELECT MIN(year), AVG(year), MAX(year), engine, manufacturer
FROM planes
GROUP BY engine, manufacturer
""", conn)

# pandas approach
task5_my = planes.groupby(['engine', 'manufacturer'])['year'].agg(['min', 'mean', 'max']).reset_index()
task5_my.columns = ['engine', 'manufacturer', 'MIN(year)', 'AVG(year)', 'MAX(year)']
task5_my = task5_my[['MIN(year)', 'AVG(year)', 'MAX(year)', 'engine', 'manufacturer']]

# Verify results match
pd.testing.assert_frame_equal(task5_sql, task5_my)
print("Query 5 verification: PASSED")
print(f"Calculated year statistics for {len(task5_my)} engine-manufacturer combinations")
Query 5 verification: PASSED
Calculated year statistics for 43 engine-manufacturer combinations

Query 6¶

This query will select the planes table with only the records in which the speed data is present. It will eliminate any rows containing no speed data, leaving with a complete set of data to apply to speed related analyses.

In [12]:
# SQL approach
task6_sql = pd.read_sql_query("""
SELECT * FROM planes WHERE speed IS NOT NULL
""", conn)

# pandas approach
task6_my = planes[planes['speed'].notna()].reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task6_sql, task6_my)
print("Query 6 verification: PASSED")
print(f"Found {len(task6_my)} planes with speed information")
Query 6 verification: PASSED
Found 23 planes with speed information

Query 7¶

The query is used to find aircraft tail numbers of those aircraft that fit particular requirements: the aircraft must have a seating count of 150 to 210 people and must be manufactured in 2011 or after that. This assists in establishing new, medium-or-large capacity aircrafts that are not that old.

In [13]:
# SQL approach
task7_sql = pd.read_sql_query("""
SELECT tailnum FROM planes
WHERE seats BETWEEN 150 AND 210 AND year >= 2011
""", conn)

# pandas approach
task7_my = planes[(planes['seats'] >= 150) & (planes['seats'] <= 210) & (planes['year'] >= 2011)][['tailnum']].reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task7_sql, task7_my)
print("Query 7 verification: PASSED")
print(f"Found {len(task7_my)} planes matching the criteria")
Query 7 verification: PASSED
Found 92 planes matching the criteria

Query 8¶

This query finds very large aircrafts (with at least 390 seats) produced by three giant aircraft manufacturers Boeing, Airbus, or Embraer. It will give the tail number, manufacturer and seat count of these high capacity planes.

In [14]:
# SQL approach
task8_sql = pd.read_sql_query("""
SELECT tailnum, manufacturer, seats FROM planes
WHERE manufacturer IN ("BOEING", "AIRBUS", "EMBRAER") AND seats>390
""", conn)

# pandas approach
task8_my = planes[(planes['manufacturer'].isin(["BOEING", "AIRBUS", "EMBRAER"])) & (planes['seats'] > 390)][['tailnum', 'manufacturer', 'seats']].reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task8_sql, task8_my)
print("Query 8 verification: PASSED")
print(f"Found {len(task8_my)} planes matching the criteria")
Query 8 verification: PASSED
Found 13 planes matching the criteria

Query 9¶

This query identifies distinct values of manufacturing year and seat count on th planes manufactured after 2012. The results are first arranged according to year in ascending order, followed by seats in descending order and this illustrates the distribution of capacities of newer aircraft.

In [15]:
# SQL approach
task9_sql = pd.read_sql_query("""
SELECT DISTINCT year, seats FROM planes
WHERE year >= 2012 ORDER BY year ASC, seats DESC
""", conn)

# pandas approach
task9_my = planes[planes['year'] >= 2012][['year', 'seats']].drop_duplicates().sort_values(['year', 'seats'], ascending=[True, False]).reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task9_sql, task9_my)
print("Query 9 verification: PASSED")
print(f"Found {len(task9_my)} unique year-seat combinations for planes from 2012 onwards")
Query 9 verification: PASSED
Found 21 unique year-seat combinations for planes from 2012 onwards

Query 10¶

The query resembles Query 9 and has different sorting priorities. It retrieves special combinations of year and seats in newer aircraft, but ranks more by the number of seats in descending order, followed by year in ascending order. This illustrates the largest capacity aircraft before the others.

In [17]:
# SQL approach
task10_sql = pd.read_sql_query("""
SELECT DISTINCT year, seats FROM planes
WHERE year >= 2012 ORDER BY seats DESC, year ASC
""", conn)

# pandas approach
task10_my = planes[planes['year'] >= 2012][['year', 'seats']].drop_duplicates().sort_values(['seats', 'year'], ascending=[False, True]).reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task10_sql, task10_my)
print("Query 10 verification: PASSED")
print(f"Retrieved {len(task10_my)} unique combinations, sorted by capacity")
Query 10 verification: PASSED
Retrieved 21 unique combinations, sorted by capacity

Query 11¶

This query calculates the number of large-capacity (over 200 seats) aircraft manufactured by each company. It then filters high capacity planes first and then it is sorted by manufacturer displaying the number of large planes by manufacturer.

In [18]:
# SQL approach
task11_sql = pd.read_sql_query("""
SELECT manufacturer, COUNT(*) FROM planes
WHERE seats > 200 GROUP BY manufacturer
""", conn)

# pandas approach
task11_my = planes[planes['seats'] > 200].groupby('manufacturer').size().reset_index(name='COUNT(*)')

# Verify results match
pd.testing.assert_frame_equal(task11_sql, task11_my)
print("Query 11 verification: PASSED")
print(f"Found {len(task11_my)} manufacturers producing large-capacity aircraft")
Query 11 verification: PASSED
Found 3 manufacturers producing large-capacity aircraft

Query 12¶

This query is used to determine manufacturers with over 10 planes in the dataset. The HAVING clause is used to screen the grouped results to identify prolific manufacturers and the companies that are very prevalent in the NYC airports fleet.

In [19]:
# SQL approach
task12_sql = pd.read_sql_query("""
SELECT manufacturer, COUNT(*) FROM planes
GROUP BY manufacturer HAVING COUNT(*) > 10
""", conn)

# pandas approach
task12_my = planes.groupby('manufacturer').size().reset_index(name='COUNT(*)')
task12_my = task12_my[task12_my['COUNT(*)'] > 10].reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task12_sql, task12_my)
print("Query 12 verification: PASSED")
print(f"Found {len(task12_my)} manufacturers with more than 10 planes")
Query 12 verification: PASSED
Found 8 manufacturers with more than 10 planes

Query 13¶

This query is a combination of filtering and aggregation to identify manufacturers that both produce large capacity aircrafts (greater than 200 seats) and have large planes (greater than 10) in the dataset. It exposes key users who are producers of high capacity aircraft.

In [20]:
# SQL approach
task13_sql = pd.read_sql_query("""
SELECT manufacturer, COUNT(*) FROM planes
WHERE seats > 200 GROUP BY manufacturer HAVING COUNT(*) > 10
""", conn)

# pandas approach
task13_my = planes[planes['seats'] > 200].groupby('manufacturer').size().reset_index(name='COUNT(*)')
task13_my = task13_my[task13_my['COUNT(*)'] > 10].reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task13_sql, task13_my)
print("Query 13 verification: PASSED")
print(f"Found {len(task13_my)} manufacturers with more than 10 large-capacity planes")
Query 13 verification: PASSED
Found 2 manufacturers with more than 10 large-capacity planes

Query 14¶

This query helps to determine the 10 manufacturers with the highest number of planes in the dataset. It counts planes per manufacturer, aliases the count as how many, sorts it in descending order and only displays the top 10. This demonstrates the concentration of the manufactures who the NYC airports fleet is dominated by.

In [21]:
# SQL approach
task14_sql = pd.read_sql_query("""
SELECT manufacturer, COUNT(*) AS howmany
FROM planes
GROUP BY manufacturer
ORDER BY howmany DESC LIMIT 10
""", conn)

# pandas approach
task14_my = planes.groupby('manufacturer').size().reset_index(name='howmany')
task14_my = task14_my.sort_values('howmany', ascending=False).head(10).reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task14_sql, task14_my)
print("Query 14 verification: PASSED")
print(f"Retrieved top 10 manufacturers by plane count")
Query 14 verification: PASSED
Retrieved top 10 manufacturers by plane count

Query 15¶

The query is a left join of the planes and flights tables where it matches with the tail number. It also adds aircraft data to the flights data such as the year of manufacture, speed, and the number of seats. The left join will make sure that all the flights are not lost when plane information is not present.

In [22]:
# SQL approach
task15_sql = pd.read_sql_query("""
SELECT
    flights.*,
    planes.year AS plane_year,
    planes.speed AS plane_speed,
    planes.seats AS plane_seats
FROM flights LEFT JOIN planes ON flights.tailnum=planes.tailnum
""", conn)

# pandas approach
task15_my = flights.merge(
    planes[['tailnum', 'year', 'speed', 'seats']],
    on='tailnum',
    how='left',
    suffixes=('', '_plane')
).rename(columns={'year_plane': 'plane_year', 'speed': 'plane_speed', 'seats': 'plane_seats'})

# Verify results match
pd.testing.assert_frame_equal(task15_sql, task15_my)
print("Query 15 verification: PASSED")
print(f"Joined {len(task15_my):,} flight records with plane information")
Query 15 verification: PASSED
Joined 336,776 flight records with plane information

Query 16¶

This complicated query does several joins in order to get the information out of three tables. The carrier-tailnums combination of flights is used as the beginning of the key, which is followed by the merger with planes into aircraft information and with airlines into carrier information. The outcome of this is the provision of comprehensive information on what airlines operate what aircraft.

In [34]:
# SQL approach
task16_sql = pd.read_sql_query("""
SELECT planes.*, airlines.* FROM
(SELECT DISTINCT carrier, tailnum FROM flights) AS cartail
INNER JOIN planes ON cartail.tailnum=planes.tailnum
INNER JOIN airlines ON cartail.carrier=airlines.carrier
""", conn)

# pandas approach
cartail = flights[['carrier', 'tailnum']].drop_duplicates()
task16_my = cartail.merge(planes, on='tailnum', how='inner')
task16_my = task16_my.merge(airlines, on='carrier', how='inner')

# Reorder columns to match SQL output: planes.* first, then airlines.*
task16_my = task16_my[['tailnum', 'year', 'type', 'manufacturer', 'model', 
                        'engines', 'seats', 'speed', 'engine', 'carrier', 'name']]


# sort SQL result
task16_sql_sorted = task16_sql.sort_values(["carrier", "tailnum"]).reset_index(drop=True)

# sort pandas result
task16_my_sorted = task16_my.sort_values(["carrier", "tailnum"]).reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task16_sql_sorted, task16_my_sorted)
print("Query 16 verification: PASSED")
print(f"Joined data for {len(task16_my_sorted)} unique carrier-plane combinations")
Query 16 verification: PASSED
Joined data for 3339 unique carrier-plane combinations

Q4: Additional Query for Postgraduate Students¶

Query 17¶

This interactive query will merge flight data of Newark (EWR) airport and daily average weather forecast. It carries out the following functions:

  1. Filters flights departing from EWR
  2. Estimates the average temperature and humidity of the weather at EWR on a daily basis.
  3. Joins these two data sets through year, month and day.

The outcome adds to the flight records an average temperature and humidity data of a specified flight on a particular day, which can be used to analyse the potential impact of weather factors on the functioning of the flight.

In [24]:
# SQL approach
task17_sql = pd.read_sql_query("""
SELECT
    flights2.*,
    atemp,
    ahumid
FROM (
    SELECT * FROM flights WHERE origin='EWR'
) AS flights2
LEFT JOIN (
    SELECT
        year, month, day,
        AVG(temp) AS atemp,
        AVG(humid) AS ahumid
    FROM weather
    WHERE origin='EWR'
    GROUP BY year, month, day
) AS weather2
ON flights2.year=weather2.year
AND flights2.month=weather2.month
AND flights2.day=weather2.day
""", conn)

# pandas approach
# First subquery: filter flights from EWR
flights2 = flights[flights['origin'] == 'EWR']

# Second subquery: calculate daily average temperature and humidity for EWR
weather2 = weather[weather['origin'] == 'EWR'].groupby(['year', 'month', 'day']).agg({
    'temp': 'mean',
    'humid': 'mean'
}).reset_index()
weather2.columns = ['year', 'month', 'day', 'atemp', 'ahumid']

# Left join the two results
task17_my = flights2.merge(weather2, on=['year', 'month', 'day'], how='left').reset_index(drop=True)

# Verify results match
pd.testing.assert_frame_equal(task17_sql, task17_my)
print("Query 17 verification: PASSED")
print(f"Joined {len(task17_my):,} EWR flights with daily weather averages")
Query 17 verification: PASSED
Joined 120,835 EWR flights with daily weather averages

Summary and Conclusion¶

This report has demonstrated that in data manipulation tasks, the two tools SQL and pandas can be used interchangeably: all 17 queries were coded in both and yielded the same result. On the way we noted the following, which are some of the critical details:

  • To use filters and whittle down data, the WHERE clauses of SQL and the ability of pandas to use a Boolean indexing are both useful, but pandas is more adaptable due to method chaining and the capacity to construct more complicated conditions.

  • To group and aggregate, the GROUP BY statement of SQL is analogous to groupby of pandas, and pandas can even support more complex aggregation with agg().

  • The SQL joins are directly related to the merge functions of pandas, and they allow inner, outer, left, and right joins to act similarly. Pandas

  • The sorting and restricting of results are also natural extensions: the ORDER BY and LIMIT in SQL are similar to sorting values in pandas and head.

Practically, pandas provides all that require in complete data wrangling - and beyond. Since it resides as part of the larger Python ecosystem, it simplifies building pipelines and dealing with more complex data types and allows easy transition between data transformation and analysis and visualization. Consequently, in Python-based contexts, pandas can be used as an alternative to conventional SQL processes, and it is powerful and flexible.

This analysis shows that pandas is not only able to generate SQL-style manipulations of data, in most respects, it offers a much more expressive and more python-native toolkit to data science tasks. Pandas can be a strong alternative to simple and complex data processing in case your existing workflow is already written in Python.

In [35]:
# Close database connection
conn.close()
print("Database connection closed successfully.")
Database connection closed successfully.