Skip to content

Commit bd82c49

Browse files
committed
make gpd an optional dependency and change returns accordingly
1 parent a33d201 commit bd82c49

1 file changed

Lines changed: 24 additions & 7 deletions

File tree

dataretrieval/waterdata_helpers.py

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
11
import httpx
22
import os
3+
import warnings
34
from typing import List, Dict, Any, Optional, Union
45
from datetime import datetime
56
import pandas as pd
67
import json
7-
import geopandas as gpd
88
from datetime import datetime
99
from zoneinfo import ZoneInfo
1010
import re
11+
try:
12+
import geopandas as gpd
13+
gpd = True
14+
except ImportError:
15+
warnings.warn("Geopandas is not installed. Data frames containing geometry will be returned as pandas DataFrames.", ImportWarning)
16+
gpd = False
17+
18+
1119

1220
BASE_API = "https://api.waterdata.usgs.gov/ogcapi/"
1321
API_VERSION = "v0"
@@ -388,18 +396,27 @@ def _get_resp_data(resp: httpx.Response) -> pd.DataFrame:
388396
pandas DataFrame containing the feature properties and each row's service-specific id.
389397
Returns an empty pandas DataFrame if no features are returned.
390398
"""
399+
# Check if it's an empty response
391400
body = resp.json()
392401
if not body.get("numberReturned"):
393402
return pd.DataFrame()
394-
#df = pd.json_normalize(
395-
# resp.json()["features"],
396-
# sep="_")
397-
#df = df.drop(columns=["type", "geometry", "AsGeoJSON(geometry)"], errors="ignore")
398-
#df.columns = [col.replace("properties_", "") for col in df.columns]
399403

404+
# If geopandas not installed, return a pandas dataframe
405+
if not gpd:
406+
df = pd.json_normalize(
407+
body["features"],
408+
sep="_")
409+
df = df.drop(columns=["type", "geometry", "AsGeoJSON(geometry)"], errors="ignore")
410+
df.columns = [col.replace("properties_", "") for col in df.columns]
411+
return df
412+
413+
# Organize json into geodataframe and make sure id column comes along.
400414
df = gpd.GeoDataFrame.from_features(body["features"])
401415
df["id"] = pd.json_normalize(body["features"])["id"].values
416+
df = df[["id"] + [col for col in df.columns if col != "id"]]
402417

418+
# If no geometry present, then return pandas dataframe. A geodataframe
419+
# is not needed.
403420
if df["geometry"].isnull().all():
404421
df = pd.DataFrame(df.drop(columns="geometry"))
405422

@@ -506,7 +523,7 @@ def _rejigger_cols(df: pd.DataFrame, properties: Optional[List[str]], output_id:
506523
507524
Returns
508525
-------
509-
pd.DataFrame
526+
pd.DataFrame or gpd.GeoDataFrame
510527
The DataFrame with columns rearranged and/or renamed according to the specified properties and output_id.
511528
"""
512529
if properties and not all(pd.isna(properties)):

0 commit comments

Comments
 (0)