import os
import time
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import pyarrow.parquet as pq20 Parquet and GeoParquet
In assignment 3 we worked with a CSV file with more than half a million rows about spill incidents in New York State. Every time we restarted the notebook we had to read the whole 100 MB file again and repeat the same cleaning steps: simplify the column names and convert the dates. Is there a way to save our cleaned data so that it comes back exactly as we left it? And can we open only the part of a big file that we need? In this lesson we answer these questions with Parquet, a file format designed for data analysis, and GeoParquet, its geospatial version.
By the end of this lesson, students will be able to:
- explain the difference between a row-based file format and a column-based file format,
- save a
pandas.DataFrameas a Parquet file and read it back, - compare a CSV file and a Parquet file by the data types they keep, their size and the time they take to read,
- read only the columns and rows they need from a Parquet file,
- save a
geopandas.GeoDataFrameas a GeoParquet file and compare it with a shapefile, and - decide which file format to use at each step of a workflow.
About the data
In this lesson we will use the two datasets from assignment 3.
The first one is the Spill Incidents dataset from the New York State Department of Environmental Conservation [1]. It is a CSV file with information about spills of petroleum and other hazardous materials: where and when each spill happened, the material and the quantity spilled.
The second one is the TIGER shapefile of the US counties from the United States Census Bureau [2].
The pandas and geopandas packages use the pyarrow package to read and write Parquet files [3].
Row-based and column-based formats
A CSV file is a row-based format. It is a plain text file where each line is one row of the table and the values in the row are separated by commas. These are three rows from our spills file, showing only four of its columns:
Spill Number,County,Spill Date,Material Family
0107132,Westchester,10/10/2001,Other
0405586,Queens,08/21/2004,Other
0204667,Bronx,08/02/2002,PetroleumEverything in a CSV file is text. The file doesn’t say whether 0107132 is a number or a code, or whether 10/10/2001 is a date. pandas has to guess each column’s data type every time it reads the file.
Apache Parquet is an open source, column-based (or columnar) format [4]. It stores the values of each column together, along with the column’s name and data type. At the end of the file there is a footer that describes its contents. The figure below shows three rows of the spills table stored in the two formats, with one color per column. The table in the figure is the clean version we will create in a moment, with simplified column names and the dates stored as dates:
Parquet files have three properties that we will see in this lesson:
- The data types are saved in the file. A date is read back as a date and a code as a code.
- The files are smaller. The values within a column are similar to each other, so they can be compressed well.
- We can read part of the file. Each column is stored separately, so we are able to read only a few columns out of the whole file.
The main differences between the two formats are:
| CSV | Parquet | |
|---|---|---|
| Layout | row by row | column by column |
| Stored as | plain text | compressed binary |
| Data types | guessed when reading the file | saved in the file |
| Reading a few columns | the whole file is read | only those columns are read |
| Can be opened in a text editor | yes | no |
Import and clean the CSV
Let’s start by importing the packages we will use:
First, we import the spills data. We also want to know how long it takes to read the file, so we will time it with the time() function from the time module. time.time() returns the current time in seconds. Calling it before and after reading the file and subtracting gives us the seconds it took:
fp_csv = os.path.join('data', 'Spill_Incidents_20261129.csv')
# Read the CSV file and time it
start = time.time()
spills = pd.read_csv(fp_csv, dtype={'Spill Number': str, 'SWIS Code': str})
csv_seconds = time.time() - startNotice the dtype parameter for pd.read_csv. The spill numbers and the SWIS codes are codes that can start with zeros, like 0107132 and 0301. With dtype we tell pandas to read these two columns as strings so the zeros are kept. Let’s check how long it too to read in the data:
print(f"Time to read the CSV file: {csv_seconds:.2f} seconds")Time to read the CSV file: 0.67 seconds
Next, we repeat the cleaning from assignment 3: we simplify the column names and convert the three columns with dates from strings to dates.
# Simplify column names
spills.columns = spills.columns.str.lower().str.replace(' ', '_')
# Convert the date columns from strings to dates
for column in ['spill_date', 'received_date', 'close_date']:
spills[column] = pd.to_datetime(spills[column])These are the data types of our clean data frame:
spills.dtypesspill_number object
program_facility_name object
street_1 object
street_2 object
locality object
county object
zip_code object
swis_code object
dec_region int64
spill_date datetime64[ns]
received_date datetime64[ns]
contributing_factor object
waterbody object
source object
close_date datetime64[ns]
material_name object
material_family object
quantity object
units object
recovered object
dtype: object
Saving to CSV
Our data is clean now. Suppose we want to save it so we don’t have to repeat the cleaning the next time we open the notebook. The to_csv() method saves a data frame as a CSV file. With index=False the index is not written to the file:
# Save the clean data as a CSV file
fp_clean_csv = os.path.join('data', 'spills_clean.csv')
spills.to_csv(fp_clean_csv, index=False)
# Read it again
spills_from_csv = pd.read_csv(fp_clean_csv)Let’s compare the data types of the data frame we saved and the one we read back:
pd.DataFrame({'clean': spills.dtypes,
'from_csv': spills_from_csv.dtypes})| clean | from_csv | |
|---|---|---|
| spill_number | object | int64 |
| program_facility_name | object | object |
| street_1 | object | object |
| street_2 | object | object |
| locality | object | object |
| county | object | object |
| zip_code | object | object |
| swis_code | object | int64 |
| dec_region | int64 | int64 |
| spill_date | datetime64[ns] | object |
| received_date | datetime64[ns] | object |
| contributing_factor | object | object |
| waterbody | object | object |
| source | object | object |
| close_date | datetime64[ns] | object |
| material_name | object | object |
| material_family | object | object |
| quantity | object | object |
| units | object | object |
| recovered | object | object |
- Which columns changed data type?
- Compare the output of
spills['spill_number'].head(3)andspills_from_csv['spill_number'].head(3). What happened to the spill numbers? - Did we get a warning or an error at any point?
The CSV file kept the values as text and lost the data types. When we read it again pandas guessed the types, and its guesses were not the ones we had set. We would need to remember to use dtype and to convert the dates every time we read the file.
The spill numbers and the SWIS codes lost their leading zeros and we did not get any warning. This is another example of a silent failure. After saving data and reading it back, check that you got what you saved.
Write and read a Parquet file
Now let’s save the same data frame as a Parquet file using the to_parquet() method:
# Save the clean data as a Parquet file
fp_parquet = os.path.join('data', 'spills.parquet')
spills.to_parquet(fp_parquet)To read it back we use the pd.read_parquet() function. We time it too:
start = time.time()
spills_from_parquet = pd.read_parquet(fp_parquet)
parquet_seconds = time.time() - start
print(f"Time to read the CSV file: {csv_seconds:.2f} seconds")
print(f"Time to read the Parquet file: {parquet_seconds:.2f} seconds")Time to read the CSV file: 0.67 seconds
Time to read the Parquet file: 0.23 seconds
The times change from one computer to another and from one run to the next, and the first time we read a Parquet file in a session can be slower.
Which file was faster to read on your computer? How many times faster?
Data types
Let’s compare the data types again, now with the three data frames:
pd.DataFrame({'clean': spills.dtypes,
'from_csv': spills_from_csv.dtypes,
'from_parquet': spills_from_parquet.dtypes})| clean | from_csv | from_parquet | |
|---|---|---|---|
| spill_number | object | int64 | object |
| program_facility_name | object | object | object |
| street_1 | object | object | object |
| street_2 | object | object | object |
| locality | object | object | object |
| county | object | object | object |
| zip_code | object | object | object |
| swis_code | object | int64 | object |
| dec_region | int64 | int64 | int64 |
| spill_date | datetime64[ns] | object | datetime64[ns] |
| received_date | datetime64[ns] | object | datetime64[ns] |
| contributing_factor | object | object | object |
| waterbody | object | object | object |
| source | object | object | object |
| close_date | datetime64[ns] | object | datetime64[ns] |
| material_name | object | object | object |
| material_family | object | object | object |
| quantity | object | object | object |
| units | object | object | object |
| recovered | object | object | object |
The data frame we read from the Parquet file has the same data types as the one we saved. The dates are dates and the codes are strings. In fact, the two data frames are equal:
# Check the Parquet data we read is the same as the data we saved
spills_from_parquet.equals(spills)True
Which was not the case for the CSV file:
# Check the CSV data we read is the same as the data we saved
spills_from_csv.equals(spills)False
File size
The os.path.getsize() function returns the size of a file in bytes. Let’s use it to compare the two files we saved, which contain the same data:
# File sizes in megabytes (1 MB = 1000^2 bytes)
csv_size = os.path.getsize(fp_clean_csv) / 1000**2
parquet_size = os.path.getsize(fp_parquet) / 1000**2
print(f"CSV file: {csv_size:.1f} MB")
print(f"Parquet file: {parquet_size:.1f} MB")
print(f"The CSV file is {csv_size / parquet_size:.1f} times bigger than the Parquet file")CSV file: 102.1 MB
Parquet file: 23.4 MB
The CSV file is 4.4 times bigger than the Parquet file
The Parquet file is several times smaller than the CSV file. One reason is that the values in a column repeat a lot. For example, the material_family column has more than half a million rows and only four different values:
spills['material_family'].value_counts()material_family
Petroleum 486371
Other 70981
Hazardous Material 17676
Oxygenates 399
Name: count, dtype: int64
A CSV file writes out Petroleum in full in every row where it appears. A Parquet file writes each different value of the column once and, for each row, it only stores a short code that points to the value. After that, each column is compressed. The figure below shows this for eight example rows that have three of the four values:
This structure shows that a Parquet file is not a text file, so we can’t read it in a text editor the way we read a CSV file. When could this be a disadvantage?
Read only what you need
So far we have read the whole Parquet file. Its main advantage shows up when we only need a part of it.
Look at the file before loading it
A Parquet file stores a description of its contents, called its metadata. The metadata includes the number of rows and the file’s schema: the name and data type of each column. We can read the metadata without loading any data, using the pyarrow.parquet module we imported as pq:
# Number of rows and columns
metadata = pq.read_metadata(fp_parquet)
print(f"Rows: {metadata.num_rows}")
print(f"Columns: {metadata.num_columns}")Rows: 575427
Columns: 20
# Names and data types of the columns
pq.read_schema(fp_parquet)spill_number: string
program_facility_name: string
street_1: string
street_2: string
locality: string
county: string
zip_code: string
swis_code: string
dec_region: int64
spill_date: timestamp[ns]
received_date: timestamp[ns]
contributing_factor: string
waterbody: string
source: string
close_date: timestamp[ns]
material_name: string
material_family: string
quantity: string
units: string
recovered: string
-- schema metadata --
pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 2720
The line after -- schema metadata -- is extra information pandas saved to rebuild the data frame.
For a file with many gigabytes of data, checking the schema first tells us which columns we need before reading any of them.
Select columns
Suppose we only need two columns of the table. To get them from a CSV file, every line of the file has to be read. With a Parquet file, the footer is read first (step 1 in the figure), since it says where each column is stored in the file. Then only the two columns we asked for are read (step 2), and the rest of the file is skipped:
The columns parameter of pd.read_parquet() takes a list with the names of the columns to read:
start = time.time()
spills_subset = pd.read_parquet(fp_parquet, columns=['county', 'spill_date'])
subset_seconds = time.time() - start
print(f"Time to read 2 of the {metadata.num_columns} columns: {subset_seconds:.2f} seconds")
spills_subset.head(3)Time to read 2 of the 20 columns: 0.01 seconds
| county | spill_date | |
|---|---|---|
| 0 | Westchester | 2001-10-10 |
| 1 | Queens | 2004-08-21 |
| 2 | Queens | 2004-08-21 |
Select rows
The filters parameter selects rows while reading the file. Each condition is a tuple with three elements, (column, operator, value), and the conditions go in a list. A row is read only if it satisfies all the conditions.
In assignment 3 we selected the petroleum spills that happened in 2023. This is how we get the same rows directly from the file:
# Conditions: petroleum spills between January 1 and December 31, 2023
conditions = [('material_family', '==', 'Petroleum'),
('spill_date', '>=', pd.Timestamp('2023-01-01')),
('spill_date', '<=', pd.Timestamp('2023-12-31'))]
petr_23 = pd.read_parquet(fp_parquet, filters=conditions)
print(f"Rows in file: {metadata.num_rows}")
print(f"Rows read: {len(petr_23)}")Rows in file: 575427
Rows read: 8470
spill_date is a column with dates, so we compare it with a date: pd.Timestamp('2023-01-01'). Comparing it with the string '2023-01-01' raises an error. This is different from selecting rows in a data frame, where pandas converts the string to a date for us.
Verify the result. Use the spills data frame to select the petroleum spills from 2023 and check that you get the same number of rows as in petr_23.
How can rows be skipped inside a file? A big Parquet file is divided into row groups, each with part of the rows, and the footer stores the smallest and the largest value of each column in each row group. With this information, the row groups that can’t have any of the rows we asked for are not read. This saves the most when the rows in the file are sorted by the column in the condition, as in the figure below:
Our spills file is small and has a single row group, which you can check with metadata.num_row_groups. So in our case no rows are skipped inside the file: the columns are read and then the rows that satisfy the conditions are kept. Skipping row groups makes a difference with bigger files.
We can use columns and filters together. The columns in the conditions don’t need to be among the columns we read:
# County and date of spills in the oxygenates material family
oxygenates = pd.read_parquet(fp_parquet,
columns=['county', 'spill_date'],
filters=[('material_family', '==', 'Oxygenates')])
oxygenates.head(3)| county | spill_date | |
|---|---|---|
| 0 | Fulton | 2004-05-03 |
| 1 | New York | 1999-06-04 |
| 2 | Queens | 1996-10-15 |
With our file the whole table fits in memory, so selecting while reading is a convenience. With a dataset that is bigger than our computer’s memory, or one stored in the cloud, reading only the columns and rows we need is what makes it possible to work with the data at all.
GeoParquet
GeoParquet is an open specification for storing vector data in Parquet files, which is being developed as an Open Geospatial Consortium (OGC) standard [5]. A GeoParquet file is a Parquet file where one of the columns holds the geometries and the file’s metadata includes the CRS. Everything we have seen about Parquet files still applies.
In the lesson about vector data formats we saw that a shapefile is a collection of several files. The figure below shows where the geometries, the other columns and the CRS are stored in each format. Matching colors mark the same information:
Let’s import the counties shapefile:
# Import the US counties shapefile
fp_shp = os.path.join('data', 'tl_2026_us_county', 'tl_2026_us_county.shp')
counties = gpd.read_file(fp_shp)
# Simplify column names
counties.columns = counties.columns.str.lower()
print(f"CRS: {counties.crs}")
counties.head(3)CRS: EPSG:4269
| statefp | countyfp | countyns | geoid | geoidfq | name | namelsad | lsad | classfp | mtfcc | csafp | cbsafp | metdivfp | funcstat | aland | awater | intptlat | intptlon | geometry | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 12 | 009 | 00295749 | 12009 | 0500000US12009 | Brevard | Brevard County | 06 | H1 | G4020 | None | 37340 | None | A | 2628767922 | 1403935652 | +28.2983112 | -080.7003334 | POLYGON ((-80.98725 28.61300, -80.98674 28.613... |
| 1 | 06 | 055 | 00277292 | 06055 | 0500000US06055 | Napa | Napa County | 06 | H1 | G4020 | 488 | 34900 | None | A | 1947608455 | 104442639 | +38.5073502 | -122.3259960 | POLYGON ((-122.10363 38.51216, -122.10365 38.5... |
| 2 | 18 | 065 | 00450359 | 18065 | 0500000US18065 | Henry | Henry County | 06 | H1 | G4020 | 294 | 35220 | None | A | 1014957933 | 7652087 | +39.9252934 | -085.3991588 | POLYGON ((-85.31955 39.78736, -85.32016 39.787... |
Write and read a GeoParquet file
A geopandas.GeoDataFrame also has a to_parquet() method, which saves it as a GeoParquet file:
# Save the counties as a GeoParquet file
fp_geoparquet = os.path.join('data', 'counties.parquet')
counties.to_parquet(fp_geoparquet)To read the file we use the gpd.read_parquet() function:
counties_from_parquet = gpd.read_parquet(fp_geoparquet)
print(f"Type: {type(counties_from_parquet)}")
print(f"Same CRS as the data we saved: {counties_from_parquet.crs == counties.crs}")
print(f"Same data as the data we saved: {counties_from_parquet.equals(counties)}")Type: <class 'geopandas.geodataframe.GeoDataFrame'>
Same CRS as the data we saved: True
Same data as the data we saved: True
We get back a geodataframe with the same data and the same CRS.
gpd.read_parquet() for GeoParquet files
pd.read_parquet() can also open a GeoParquet file, but it returns a pandas.DataFrame where the geometry column is not a column of geometries and the CRS is missing. To get a geopandas.GeoDataFrame, read the file with gpd.read_parquet().
File size
Let’s compare the size of the shapefile with the size of the GeoParquet file. A shapefile is a collection of several files, so to get its size we add up the sizes of all the files in its folder. The os.listdir() function returns a list with the names of the files in a folder:
# Add the sizes of all the files in the shapefile's folder
shp_folder = os.path.join('data', 'tl_2026_us_county')
shp_size = 0
for file in os.listdir(shp_folder):
shp_size = shp_size + os.path.getsize(os.path.join(shp_folder, file))
shp_size = shp_size / 1000**2
geoparquet_size = os.path.getsize(fp_geoparquet) / 1000**2
print(f"Shapefile: {shp_size:.1f} MB")
print(f"GeoParquet file: {geoparquet_size:.1f} MB")Shapefile: 133.5 MB
GeoParquet file: 126.1 MB
This time the two sizes are almost the same! Nearly all the space in this dataset is taken by the coordinates of the county boundaries. These are numbers with many digits that don’t repeat, so they are not compressed much.
How much smaller a Parquet file is depends on the data, so we should measure it instead of assuming it.
Select columns and rows
gpd.read_parquet() also accepts the columns and filters parameters. When we use columns, the geometry column must be in the list. Let’s read only the name, land area and geometry of the counties in New York State, which has state code 36. The statefp column is stored as strings, so in the condition we compare it with the string '36':
# Read three columns of the NY counties
ny_counties = gpd.read_parquet(fp_geoparquet,
columns=['name', 'aland', 'geometry'],
filters=[('statefp', '==', '36')])
print(f"Counties in the file: {len(counties)}")
print(f"Counties read: {len(ny_counties)}")
ny_counties.head(3)Counties in the file: 3235
Counties read: 62
| name | aland | geometry | |
|---|---|---|---|
| 0 | Erie | 2700743371 | POLYGON ((-78.77760 42.46188, -78.77756 42.461... |
| 1 | Niagara | 1352876142 | POLYGON ((-78.49165 43.08396, -78.49179 43.084... |
| 2 | Jefferson | 3283928401 | POLYGON ((-75.90417 43.69796, -75.90437 43.697... |
Column names
We also saw that a shapefile cuts column names to 10 characters. Let’s see what this looks like. The aland column has the land area of each county in square meters. We add a column with the land area in square kilometers:
ny_counties['land_area_km2'] = ny_counties['aland'] / 1000**2
ny_counties.columnsIndex(['name', 'aland', 'geometry', 'land_area_km2'], dtype='object')
Then we save the geodataframe in the two formats. The to_file() method saves a geodataframe as a shapefile when the file name ends in .shp:
# Save the NY counties as a shapefile
fp_ny_shp = os.path.join('data', 'ny_counties.shp')
ny_counties.to_file(fp_ny_shp)
# Save the NY counties as a GeoParquet file
fp_ny_geoparquet = os.path.join('data', 'ny_counties.parquet')
ny_counties.to_parquet(fp_ny_geoparquet)/var/folders/4y/svv5420s5y32zxkvwtd0qplr0000gq/T/ipykernel_41111/4290806575.py:3: UserWarning: Column names longer than 10 characters will be truncated when saved to ESRI Shapefile.
ny_counties.to_file(fp_ny_shp)
Notice the warning about the column names that we got when saving the shapefile. Now let’s read both files and look at their column names:
ny_from_shp = gpd.read_file(fp_ny_shp)
ny_from_geoparquet = gpd.read_parquet(fp_ny_geoparquet)
print(f"Original: {list(ny_counties.columns)}")
print(f"From shapefile: {list(ny_from_shp.columns)}")
print(f"From GeoParquet: {list(ny_from_geoparquet.columns)}")Original: ['name', 'aland', 'geometry', 'land_area_km2']
From shapefile: ['name', 'aland', 'land_area_', 'geometry']
From GeoParquet: ['name', 'aland', 'geometry', 'land_area_km2']
- Which column name changed, and in which file?
- Look at your
datafolder. How many files were created forny_counties.shp? How many forny_counties.parquet?
To summarize the differences between the two formats:
| Shapefile | GeoParquet | |
|---|---|---|
| Number of files | several (.shp, .shx, .dbf, .prj, …) |
one |
| Column names | cut to 10 characters | complete |
| CRS | in a separate .prj file |
inside the file |
Which format should I use?
In this lesson we saved our clean data in two ways. When we saved it as a CSV file, the data types had to be fixed again after reading the file. When we saved it as a Parquet file, the data came back as we left it, and we could read only the columns and rows we needed. This doesn’t mean Parquet is always the best choice. The right file format depends on what the file is for and who will open it:
Parquet is also the format to use when tabular data is too big to read whole, since we can read it by parts.
Parquet and GeoParquet are also common formats for big datasets stored in the cloud. For example, Microsoft Planetary Computer publishes the US Census data as GeoParquet files.
Parquet files are data files. Just like CSV files and shapefiles, they go in the data directory of your repository and generally should not be committed.
Exercises
Answer the following questions reading only the columns and rows you need from spills.parquet.
How many rows correspond to spills in the
'Hazardous Material'material family?Read the
countyandreceived_datecolumns for the spills received on or after January 1, 2026. Which three counties have the most rows?Check your answer to question 1 using the
spillsdata frame.
Discuss with a partner. For each situation, which file format would you choose and why?
- You cleaned a table with 200 rows of field observations and need to email it to a collaborator who works with Excel.
- Your final project has one notebook that cleans a large table and a second notebook that makes the plots.
- You need the names and locations of the buildings in one neighborhood, and the full dataset has many columns and covers the whole world.
- A government agency asks you to submit your fire perimeters and their submission form only accepts shapefiles.






