USGS dataretrieval Python Package get_gwlevels() Examples

This notebook provides examples of using the Python dataretrieval package to retrieve groundwater level data for a United States Geological Survey (USGS) monitoring site. The dataretrieval package provides a collection of functions to get data from the USGS National Water Information System (NWIS) and other online sources of hydrology and water quality data, including the United States Environmental Protection Agency (USEPA).

Install the Package

Use the following code to install the package if it doesn’t exist already within your Jupyter Python environment.

[1]:
!pip install dataretrieval
Requirement already satisfied: dataretrieval in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (0.1.dev1+g2c775e4c4)
Requirement already satisfied: requests in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from dataretrieval) (2.32.5)
Requirement already satisfied: pandas<4.0.0,>=2.0.0 in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from dataretrieval) (3.0.1)
Requirement already satisfied: numpy>=1.26.0 in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from pandas<4.0.0,>=2.0.0->dataretrieval) (2.4.3)
Requirement already satisfied: python-dateutil>=2.8.2 in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from pandas<4.0.0,>=2.0.0->dataretrieval) (2.9.0.post0)
Requirement already satisfied: six>=1.5 in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from python-dateutil>=2.8.2->pandas<4.0.0,>=2.0.0->dataretrieval) (1.17.0)
Requirement already satisfied: charset_normalizer<4,>=2 in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from requests->dataretrieval) (3.4.6)
Requirement already satisfied: idna<4,>=2.5 in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from requests->dataretrieval) (3.11)
Requirement already satisfied: urllib3<3,>=1.21.1 in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from requests->dataretrieval) (2.6.3)
Requirement already satisfied: certifi>=2017.4.17 in /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages (from requests->dataretrieval) (2026.2.25)

Load the package so you can use it along with other packages used in this notebook.

[2]:
from IPython.display import display

from dataretrieval import nwis

Basic Usage

The dataretrieval package has several functions that allow you to retrieve data from different web services. This examples uses the get_gwlevels() function to retrieve groundwater level data from USGS NWIS. The following arguments are supported:

Arguments (Additional parameters, if supplied, will be used as query parameters)

  • sites (string or list of strings): A list of USGS site identifiers for which to retrieve data.

  • start (string): The beginning date for a period for which to retrieve data. If the waterdata parameter begin_date is supplied, it will overwrite the start parameter (defaults to ‘1851-01-01’)

  • end (string): The ending date for a period for which to retrieve data. If the waterdata parameter end_date is supplied, it will overwrite the end parameter.

Example 1: Get groundwater level data for a single monitoring site.

[3]:
# Set the parameters needed to retrieve data
site_id = "434400121275801"

# Retrieve the data
data = nwis.get_gwlevels(sites=site_id)
print("Retrieved " + str(len(data[0])) + " data values.")
Retrieved 0 data values.

Interpreting the Result

The result of calling the get_gwlevels() function is an object that contains a Pandas data frame and an associated metadata object. The Pandas data frame contains the data requested. The data frame is indexed by the dates associated with the data values.

Once you’ve got the data frame, there’s several useful things you can do to explore the data.

Display the data frame as a table

[4]:
display(data[0])
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Error report</title><style type="text/css"><!--H1 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:TahomaArialsans-serif;color:black;background-color:white;} B {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;} P {font-family:TahomaArialsans-serif;background:white;color:black;font-size:12px;}A {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 503 - Service unavailable please try again later or contact gs-w_support_nwisweb@usgs.gov. server=[caas01]</h1><hr/><p><b>type</b> Status report</p><p><b>message</b>Service unavailable please try again later or contact gs-w_support_nwisweb@usgs.gov. server=[caas01]</p><p><b>description</b>The requested service is not currently available.</p><hr/><h3>Error Report</h3></body></html>

Show the data types of the columns in the resulting data frame.

[5]:
print(data[0].dtypes)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Error report</title><style type="text/css"><!--H1 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:TahomaArialsans-serif;color:black;background-color:white;} B {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;} P {font-family:TahomaArialsans-serif;background:white;color:black;font-size:12px;}A {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 503 - Service unavailable please try again later or contact gs-w_support_nwisweb@usgs.gov. server=[caas01]</h1><hr/><p><b>type</b> Status report</p><p><b>message</b>Service unavailable please try again later or contact gs-w_support_nwisweb@usgs.gov. server=[caas01]</p><p><b>description</b>The requested service is not currently available.</p><hr/><h3>Error Report</h3></body></html>    object
dtype: object

Get summary statistics for the daily streamflow values.

[6]:
data[0]["lev_va"].describe()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages/pandas/core/indexes/base.py:3641, in Index.get_loc(self, key)
   3640 try:
-> 3641     return self._engine.get_loc(casted_key)
   3642 except KeyError as err:

File pandas/_libs/index.pyx:168, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/index.pyx:197, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/hashtable_class_helper.pxi:7668, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas/_libs/hashtable_class_helper.pxi:7676, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'lev_va'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[6], line 1
----> 1 data[0]["lev_va"].describe()

File /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages/pandas/core/frame.py:4378, in DataFrame.__getitem__(self, key)
   4376 if self.columns.nlevels > 1:
   4377     return self._getitem_multilevel(key)
-> 4378 indexer = self.columns.get_loc(key)
   4379 if is_integer(indexer):
   4380     indexer = [indexer]

File /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages/pandas/core/indexes/base.py:3648, in Index.get_loc(self, key)
   3643     if isinstance(casted_key, slice) or (
   3644         isinstance(casted_key, abc.Iterable)
   3645         and any(isinstance(x, slice) for x in casted_key)
   3646     ):
   3647         raise InvalidIndexError(key) from err
-> 3648     raise KeyError(key) from err
   3649 except TypeError:
   3650     # If we have a listlike key, _check_indexing_error will raise
   3651     #  InvalidIndexError. Otherwise we fall through and re-raise
   3652     #  the TypeError.
   3653     self._check_indexing_error(key)

KeyError: 'lev_va'

Make a quick time series plot.

[7]:
ax = data[0].plot(x="lev_dt", y="lev_va")
ax.set_xlabel("Date")
ax.set_ylabel("Water Level (feet below land surface)")
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages/pandas/core/indexes/base.py:3641, in Index.get_loc(self, key)
   3640 try:
-> 3641     return self._engine.get_loc(casted_key)
   3642 except KeyError as err:

File pandas/_libs/index.pyx:168, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/index.pyx:197, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/hashtable_class_helper.pxi:7668, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas/_libs/hashtable_class_helper.pxi:7676, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'lev_dt'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[7], line 1
----> 1 ax = data[0].plot(x="lev_dt", y="lev_va")
      2 ax.set_xlabel("Date")
      3 ax.set_ylabel("Water Level (feet below land surface)")

File /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages/pandas/plotting/_core.py:1149, in PlotAccessor.__call__(self, *args, **kwargs)
   1147 if is_integer(x) and not holds_integer(data.columns):
   1148     x = data_cols[x]
-> 1149 elif not isinstance(data[x], ABCSeries):
   1150     raise ValueError("x must be a label or position")
   1151 data = data.set_index(x)

File /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages/pandas/core/frame.py:4378, in DataFrame.__getitem__(self, key)
   4376 if self.columns.nlevels > 1:
   4377     return self._getitem_multilevel(key)
-> 4378 indexer = self.columns.get_loc(key)
   4379 if is_integer(indexer):
   4380     indexer = [indexer]

File /opt/hostedtoolcache/Python/3.13.12/x64/lib/python3.13/site-packages/pandas/core/indexes/base.py:3648, in Index.get_loc(self, key)
   3643     if isinstance(casted_key, slice) or (
   3644         isinstance(casted_key, abc.Iterable)
   3645         and any(isinstance(x, slice) for x in casted_key)
   3646     ):
   3647         raise InvalidIndexError(key) from err
-> 3648     raise KeyError(key) from err
   3649 except TypeError:
   3650     # If we have a listlike key, _check_indexing_error will raise
   3651     #  InvalidIndexError. Otherwise we fall through and re-raise
   3652     #  the TypeError.
   3653     self._check_indexing_error(key)

KeyError: 'lev_dt'

The other part of the result returned from the get_gwlevels() function is a metadata object that contains information about the query that was executed to return the data. For example, you can access the URL that was assembled to retrieve the requested data from the USGS web service. The USGS web service responses contain a descriptive header that defines and can be helpful in interpreting the contents of the response.

[8]:
print("The query URL used to retrieve the data from  NWIS was: " + data[1].url)
The query URL used to retrieve the data from  NWIS was: https://waterservices.usgs.gov/nwis/gwlevels?format=rdb&startDT=1851-01-01&sites=434400121275801

Additional Examples

You can also request data for multiple sites at the same time.

Example 2: Get data for multiple sites. Site numbers are specified using a comma delimited list of strings.

[9]:
site_ids = ["434400121275801", "375907091432201"]
data2 = nwis.get_gwlevels(sites=site_ids)
print("Retrieved " + str(len(data2[0])) + " data values.")
display(data2[0])
Retrieved 0 data values.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Error report</title><style type="text/css"><!--H1 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:TahomaArialsans-serif;color:black;background-color:white;} B {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;} P {font-family:TahomaArialsans-serif;background:white;color:black;font-size:12px;}A {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 503 - Service unavailable please try again later or contact gs-w_support_nwisweb@usgs.gov. server=[caas01]</h1><hr/><p><b>type</b> Status report</p><p><b>message</b>Service unavailable please try again later or contact gs-w_support_nwisweb@usgs.gov. server=[caas01]</p><p><b>description</b>The requested service is not currently available.</p><hr/><h3>Error Report</h3></body></html>

The following example is the same as the previous example but with multi index turned off (multi_index=False)

[10]:
site_ids = ["434400121275801", "375907091432201"]
data2 = nwis.get_gwlevels(sites=site_ids, multi_index=False)
print("Retrieved " + str(len(data2[0])) + " data values.")
display(data2[0])
Retrieved 0 data values.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Error report</title><style type="text/css"><!--H1 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:TahomaArialsans-serif;color:black;background-color:white;} B {font-family:TahomaArialsans-serif;color:white;background-color:#525D76;} P {font-family:TahomaArialsans-serif;background:white;color:black;font-size:12px;}A {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 503 - Service unavailable please try again later or contact gs-w_support_nwisweb@usgs.gov. server=[vaas01]</h1><hr/><p><b>type</b> Status report</p><p><b>message</b>Service unavailable please try again later or contact gs-w_support_nwisweb@usgs.gov. server=[vaas01]</p><p><b>description</b>The requested service is not currently available.</p><hr/><h3>Error Report</h3></body></html>

Some groundwater level data have dates that include only a year or a month and year, but no day.

Example 3: Retrieve groundwater level data that have dates without a day.

[11]:
data3 = nwis.get_gwlevels(sites="425957088141001")
print("Retrieved " + str(len(data3[0])) + " data values.")

# Print the date/time index values, which show up as NaT because
# the dates can't be converted to a date/time data type
print(data3[0].index)
Retrieved 0 data values.
RangeIndex(start=0, stop=0, step=1)

If you want to see the USGS RDB (delimited text) version of the data just retrieved, you can get the URL for the request that was sent to the USGS web service.

[12]:
# Print the URL used to retrieve the data
print("You can examine the data retrieved from NWIS at: " + data3[1].url)
You can examine the data retrieved from NWIS at: https://waterservices.usgs.gov/nwis/gwlevels?format=rdb&startDT=1851-01-01&sites=425957088141001

You can also retrieve data for a site within a specified time window by specifying a start date and an end date.

Example 4: Get groundwater level data for a site between a startDate and endDate.

[13]:
data4 = nwis.get_gwlevels(sites=site_id, start="1980-01-01", end="2000-12-31")
print("Retrieved " + str(len(data4[0])) + " data values.")
Retrieved 0 data values.