Skip to content

Commit 98017da

Browse files
author
Mike Hearne
authored
Merge pull request #255 from mhearne-usgs/appendfix
Replaced instances of deprecated dataframe.append with other methods …
2 parents 7e65edb + 66384e4 commit 98017da

4 files changed

Lines changed: 57 additions & 50 deletions

File tree

install.sh

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/bin/bash
22

3+
cwd=$(pwd)
34
unamestr=`uname`
45
env_file=environment.yml
56
if [ "$unamestr" == 'Linux' ]; then
@@ -71,6 +72,9 @@ if [ $? -ne 0 ]; then
7172
echo ". $_CONDA_ROOT/etc/profile.d/conda.sh" >> $prof
7273
fi
7374

75+
# make sure we're in the project directory still
76+
cd $cwd
77+
7478
# Start in conda base environment
7579
echo "Activate base virtual environment"
7680
conda activate base
@@ -80,12 +84,12 @@ conda remove -y -n $VENV --all
8084

8185
# Package list:
8286
package_list=(
83-
"python>=3.6"
87+
"python>=3.7"
8488
"impactutils"
8589
"fiona>=1.8.20"
8690
"ipython"
8791
"jupyter"
88-
"numpy"
92+
"numpy=1.21"
8993
"obspy"
9094
"pandas"
9195
"pip"

libcomcat/classes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -767,7 +767,7 @@ def getProducts(self, product_name, source="preferred", version="preferred"):
767767
dft = df[df["source"] == psource]
768768
dft = dft.sort_values("time")
769769
dft["version"] = np.arange(1, len(dft) + 1)
770-
newframe = newframe.append(dft)
770+
newframe = pd.concat([newframe, dft])
771771
df = newframe
772772

773773
if source == "preferred":

libcomcat/dataframes.py

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -119,19 +119,6 @@ def get_phase_dataframe(detail, catalog="preferred"):
119119
"""
120120
if catalog is None:
121121
catalog = "preferred"
122-
df = pd.DataFrame(
123-
columns=[
124-
"Channel",
125-
"Distance",
126-
"Azimuth",
127-
"Phase",
128-
"Arrival Time",
129-
"Status",
130-
"Residual",
131-
"Weight",
132-
"Agency",
133-
]
134-
)
135122

136123
phasedata = detail.getProducts("phase-data", source=catalog)[0]
137124
quakeurl = phasedata.getContentURL("quakeml.xml")
@@ -150,14 +137,28 @@ def get_phase_dataframe(detail, catalog="preferred"):
150137
msg = fmt % (quakeurl, str(e))
151138
raise ParsingError(msg)
152139
catevent = catalog.events[0]
140+
phaserows = []
153141
for pick in catevent.picks:
154142
station = pick.waveform_id.station_code
155143
fmt = "Getting pick %s for station%s..."
156144
logging.debug(fmt % (pick.time, station))
157145
phaserow = _get_phaserow(pick, catevent)
158146
if phaserow is None:
159147
continue
160-
df = df.append(phaserow, ignore_index=True)
148+
phaserows.append(phaserow)
149+
df = pd.DataFrame(phaserows)
150+
columns = [
151+
"Channel",
152+
"Distance",
153+
"Azimuth",
154+
"Phase",
155+
"Arrival Time",
156+
"Status",
157+
"Residual",
158+
"Weight",
159+
"Agency",
160+
]
161+
df = df[columns]
161162
return df
162163

163164

@@ -319,7 +320,7 @@ def get_magnitude_data_frame(detail, catalog, magtype):
319320
AttributeError if input DetailEvent does not have a phase-data product
320321
for the input catalog.
321322
"""
322-
columns = columns = [
323+
columns = [
323324
"Channel",
324325
"Type",
325326
"Amplitude",
@@ -331,7 +332,6 @@ def get_magnitude_data_frame(detail, catalog, magtype):
331332
"Azimuth",
332333
"MeasurementTime",
333334
]
334-
df = pd.DataFrame(columns=columns)
335335
phasedata = detail.getProducts("phase-data", source=catalog)[0]
336336
quakeurl = phasedata.getContentURL("quakeml.xml")
337337
try:
@@ -350,6 +350,7 @@ def get_magnitude_data_frame(detail, catalog, magtype):
350350
msg = fmt % (quakeurl, str(e))
351351
raise ParsingError(msg)
352352
catevent = catalog.events[0] # match this to input catalog
353+
rows = []
353354
for magnitude in catevent.magnitudes:
354355
if magnitude.magnitude_type.lower() != magtype.lower():
355356
continue
@@ -403,8 +404,9 @@ def get_magnitude_data_frame(detail, catalog, magtype):
403404
row["Weight"] = contribution.weight
404405
row["Distance"] = distance
405406
row["Azimuth"] = azimuth
407+
rows.append(row)
406408

407-
df = df.append(row, ignore_index=True)
409+
df = pd.DataFrame(rows)
408410
df = df[columns]
409411
return df
410412

@@ -548,7 +550,7 @@ def get_pager_data_frame(
548550
if not detail.hasProduct("losspager"):
549551
return None
550552

551-
df = None
553+
total_rows = []
552554
for pager in detail.getProducts("losspager", version="all"):
553555
total_row = {}
554556
default = {}
@@ -645,12 +647,11 @@ def get_pager_data_frame(
645647
"predicted_dollars",
646648
"dollars_sigma",
647649
]
648-
if df is None:
649-
df = pd.DataFrame(columns=columns)
650-
df = df.append(total_row, ignore_index=True)
650+
total_rows.append(total_row)
651651
for ccode, country_row in country_rows.items():
652-
df = df.append(country_row, ignore_index=True)
652+
total_rows.append(country_row)
653653

654+
df = pd.DataFrame(total_rows)
654655
df = df[columns]
655656
# countries with zero fatalities don't report, so fill in with zeros
656657
if get_losses:
@@ -1002,24 +1003,25 @@ def get_history_data_frame(detail, products=None):
10021003
else:
10031004
products = PRODUCTS
10041005

1005-
dataframe = pd.DataFrame(columns=PRODUCT_COLUMNS)
1006+
allrows = []
10061007
for product in products:
10071008
logging.debug("Searching for %s products..." % product)
10081009
if not event.hasProduct(product):
10091010
continue
10101011
prows = _get_product_rows(event, product)
1011-
dataframe = dataframe.append(prows, ignore_index=True)
1012+
allrows += prows
10121013

1013-
dataframe = dataframe.sort_values("Update Time")
1014-
dataframe["Elapsed (min)"] = np.round(dataframe["Elapsed (min)"], 1)
1014+
dataframe = pd.DataFrame(allrows)
10151015
dataframe["Comment"] = ""
10161016
dataframe = dataframe[PRODUCT_COLUMNS]
1017+
dataframe = dataframe.sort_values("Update Time")
1018+
dataframe["Elapsed (min)"] = np.round(dataframe["Elapsed (min)"], 1)
10171019
return (dataframe, event)
10181020

10191021

10201022
def _get_product_rows(event, product_name):
10211023
products = event.getProducts(product_name, source="all", version="all")
1022-
prows = pd.DataFrame(columns=PRODUCT_COLUMNS)
1024+
prows = []
10231025
for product in products:
10241026
# if product.contents == ['']:
10251027
# continue
@@ -1047,7 +1049,7 @@ def _get_product_rows(event, product_name):
10471049
continue
10481050
if prow is None:
10491051
continue
1050-
prows = prows.append(prow, ignore_index=True)
1052+
prows.append(prow)
10511053

10521054
return prows
10531055

@@ -1774,6 +1776,7 @@ def split_history_frame(dataframe, product=None):
17741776
parts = dataframe.iloc[0]["Description"].split("|")
17751777
columns = [p.split("#")[0] for p in parts]
17761778
df2 = pd.DataFrame(columns=columns)
1779+
hrows = []
17771780
for idx, row in dataframe.iterrows():
17781781
parts = row["Description"].split("|")
17791782
columns = [p.split("#")[0].strip() for p in parts]
@@ -1790,8 +1793,9 @@ def split_history_frame(dataframe, product=None):
17901793
newvalues.append(newval)
17911794
ddict = dict(zip(columns, newvalues))
17921795
row = pd.Series(ddict)
1793-
df2 = df2.append(row, ignore_index=True)
1796+
hrows.append(row)
17941797

1798+
df2 = pd.DataFrame(hrows)
17951799
dataframe = dataframe.reset_index(drop=True)
17961800
df2 = df2.reset_index(drop=True)
17971801
dataframe = pd.concat([dataframe, df2], axis=1)
@@ -2114,7 +2118,7 @@ def associate(
21142118
dlabels = ["dtime", "ddist", "dmag", "asq", "bsq", "csq", "psum"]
21152119
talternates.drop(labels=dlabels, axis="columns", inplace=True)
21162120
talternates["chosen_id"] = ef_row["id"]
2117-
alternates = alternates.append(talternates)
2121+
alternates = pd.concat([alternates, talternates])
21182122

21192123
found_events.append(row)
21202124
associated = pd.DataFrame(found_events)

tests/libcomcat/dataframes_test.py

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -152,23 +152,22 @@ def test_history_data_frame():
152152
# SMOKE TEST
153153
cassettes, datadir = get_datadir()
154154
tape_file = os.path.join(cassettes, "dataframes_history.yaml")
155+
products = [
156+
"shakemap",
157+
"dyfi",
158+
"losspager",
159+
"oaf",
160+
"finite-fault",
161+
"focal-mechanism",
162+
"ground-failure",
163+
"moment-tensor",
164+
"phase-data",
165+
"origin",
166+
]
167+
155168
with vcr.use_cassette(tape_file, record_mode="new_episodes"):
156169
nc72852151 = get_event_by_id("nc72852151", includesuperseded=True)
157-
(history, event) = get_history_data_frame(
158-
nc72852151,
159-
[
160-
"shakemap",
161-
"dyfi",
162-
"losspager",
163-
"oaf",
164-
"finite-fault",
165-
"focal-mechanism",
166-
"ground-failure",
167-
"moment-tensor",
168-
"phase-data",
169-
"origin",
170-
],
171-
)
170+
(history, event) = get_history_data_frame(nc72852151, products)
172171
us10008e3k = get_event_by_id("us10008e3k", includesuperseded=True)
173172
(history, event) = get_history_data_frame(
174173
us10008e3k,
@@ -415,6 +414,8 @@ def test_associate():
415414

416415

417416
if __name__ == "__main__":
417+
print("Testing history frame...")
418+
test_history_data_frame()
418419
print("Testing catalog association...")
419420
test_associate()
420421
print("Testing nan mags extraction...")
@@ -431,5 +432,3 @@ def test_associate():
431432
test_get_detail_data_frame()
432433
print("Testing magnitude frame...")
433434
test_magnitude_dataframe()
434-
print("Testing history frame...")
435-
test_history_data_frame()

0 commit comments

Comments
 (0)