Skip to content

Commit 4c6a1f8

Browse files
authored
x2sys_cross: Fix IndexError to allow empty dataframe outputs (#4060)
Fixes `IndexError: index 0 is out of bounds for axis 0 with size 0` when x2sys_cross returns no crossovers. An empty dataframe should be returned instead. Do so by not checking column names when the dataframe is empty due to no available crossovers.
1 parent 01f64bf commit 4c6a1f8

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

pygmt/src/x2sys_cross.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -250,9 +250,12 @@ def x2sys_cross(
250250
unit = time_unit.upper() if time_unit in "wd" else time_unit
251251
scale = 1.0
252252

253-
columns = result.columns[2:4]
254-
result[columns] *= scale
255-
result[columns] = result[columns].apply(pd.to_timedelta, unit=unit)
256-
if columns[0][0] == "t": # "t" or "i":
257-
result[columns] += pd.Timestamp(lib.get_default("TIME_EPOCH"))
253+
if len(result) > 0: # if crossovers exist (more than one output row)
254+
columns: pd.Index = result.columns[2:4] # i_1/i_2 or t_1/t_2 columns
255+
result[columns] *= scale
256+
result[columns] = result[columns].apply(pd.to_timedelta, unit=unit)
257+
258+
if columns[0][0] == "t": # "t" or "i":
259+
result[columns] += pd.Timestamp(lib.get_default("TIME_EPOCH"))
260+
258261
return result

pygmt/tests/test_x2sys_cross.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,3 +308,26 @@ def test_x2sys_cross_trackvalues():
308308
assert output.shape == (14338, 12)
309309
npt.assert_allclose(output.z_1.mean(), -2422.418556, rtol=1e-4)
310310
npt.assert_allclose(output.z_2.mean(), -2402.268364, rtol=1e-4)
311+
312+
313+
@pytest.mark.usefixtures("mock_x2sys_home")
314+
def test_x2sys_cross_output_dataframe_empty(tracks):
315+
"""
316+
Test that x2sys_cross can output an empty dataframe (when there are no crossovers)
317+
without any errors.
318+
319+
Regression test for
320+
https://forum.generic-mapping-tools.org/t/issue-with-x2sys-in-pygmt-solved/6154
321+
"""
322+
with TemporaryDirectory(prefix="X2SYS", dir=Path.cwd()) as tmpdir:
323+
tag = Path(tmpdir).name
324+
x2sys_init(tag=tag, fmtfile="xyz", force=True)
325+
326+
tracks = [tracks[0][:5]] # subset to less rows so there won't be crossovers
327+
output = x2sys_cross(tracks=tracks, tag=tag, coe="i")
328+
329+
assert isinstance(output, pd.DataFrame)
330+
assert output.shape == (0, 0)
331+
assert output.empty
332+
columns = list(output.columns)
333+
assert columns == []

0 commit comments

Comments
 (0)