Skip to content

Commit c27af43

Browse files
authored
fix(mfdataplist): raise proper MFDataException on wrong col count (#2766)
Fix a minor issue mentioned in #2758. When a dataframe passed to set_data() has the wrong column count, the intended error would not be raised, instead you'd get a KeyError.
1 parent 8a2d055 commit c27af43

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

autotest/test_mf6.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from shutil import copytree, which
55

66
import numpy as np
7+
import pandas as pd
78
import pytest
89
from modflow_devtools.markers import requires_exe, requires_pkg
910
from modflow_devtools.misc import set_dir
@@ -58,6 +59,7 @@
5859
)
5960
from flopy.mf6.data.mffileaccess import MFFileAccessArray
6061
from flopy.mf6.data.mfstructure import MFDataItemStructure, MFDataStructure
62+
from flopy.mf6.mfbase import MFDataException
6163
from flopy.mf6.mfsimbase import MFSimulationData
6264
from flopy.mf6.modflow import (
6365
mfgwf,
@@ -1450,6 +1452,28 @@ def test_get_set_data_record(function_tmpdir):
14501452
sim.write_simulation()
14511453

14521454

1455+
def test_set_data_dataframe_column_mismatch_error(function_tmpdir):
1456+
"""
1457+
DataFrame with a wrong column count should raise MFDataException.
1458+
Previously the error message code referenced len(data[0]), which on a
1459+
DataFrame accesses the column named 0 and raises KeyError instead.
1460+
"""
1461+
sim = MFSimulation(sim_ws=str(function_tmpdir), exe_name="mf6")
1462+
ModflowTdis(sim, nper=1, perioddata=[(1.0, 1, 1.0)])
1463+
ModflowIms(sim)
1464+
gwf = ModflowGwf(sim, modelname="gwf")
1465+
ModflowGwfdis(gwf, nlay=1, nrow=10, ncol=10)
1466+
ModflowGwfic(gwf, strt=0.0)
1467+
ModflowGwfnpf(gwf)
1468+
ModflowGwfwel(gwf, stress_period_data={0: [[(0, 0, 0), -1.0]]})
1469+
spd = gwf.get_package("WEL").stress_period_data
1470+
1471+
# 3 columns: matches neither _header_names (4) nor _data_item_names (2)
1472+
df = pd.DataFrame({"a": [0], "b": [3], "c": [-500.0]})
1473+
with pytest.raises(MFDataException):
1474+
spd.set_data({0: df})
1475+
1476+
14531477
@requires_exe("mf6")
14541478
def test_output(function_tmpdir, example_data_path):
14551479
ex_name = "test001e_UZF_3lay"

flopy/mf6/data/mfdataplist.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -757,7 +757,7 @@ def set_data(self, data, autofill=False, check_data=True, append=False):
757757
message = (
758758
f"ERROR: Data list {self._data_name} supplied the "
759759
f"wrong number of columns of data, expected "
760-
f"{len(self._data_item_names)} got {len(data[0])}.\n"
760+
f"{len(self._data_item_names)} got {len(data.columns)}.\n"
761761
f"Data columns supplied: {data.columns}\n"
762762
f"Data columns expected: {self._header_names}"
763763
)

0 commit comments

Comments
 (0)