Skip to content

Commit e84b9ee

Browse files
authored
BUG: No error raised in to_stata() for -np.inf #45350 (#45360)
1 parent 96f2f2a commit e84b9ee

File tree

3 files changed

+12
-18
lines changed

3 files changed

+12
-18
lines changed

doc/source/whatsnew/v1.5.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ MultiIndex
171171

172172
I/O
173173
^^^
174-
-
174+
- Bug in :meth:`DataFrame.to_stata` where no error is raised if the :class:`DataFrame` contains ``-np.inf`` (:issue:`45350`)
175175
-
176176

177177
Period

pandas/io/stata.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -625,12 +625,12 @@ def _cast_to_stata_types(data: DataFrame) -> DataFrame:
625625
if data[col].max() >= 2 ** 53 or data[col].min() <= -(2 ** 53):
626626
ws = precision_loss_doc.format("int64", "float64")
627627
elif dtype in (np.float32, np.float64):
628-
value = data[col].max()
629-
if np.isinf(value):
628+
if np.isinf(data[col]).any():
630629
raise ValueError(
631-
f"Column {col} has a maximum value of infinity which is outside "
632-
"the range supported by Stata."
630+
f"Column {col} contains infinity or -infinity"
631+
"which is outside the range supported by Stata."
633632
)
633+
value = data[col].max()
634634
if dtype == np.float32 and value > float32_max:
635635
data[col] = data[col].astype(np.float64)
636636
elif dtype == np.float64:

pandas/tests/io/test_stata.py

+7-13
Original file line numberDiff line numberDiff line change
@@ -1473,15 +1473,6 @@ def test_out_of_range_double(self):
14731473
with tm.ensure_clean() as path:
14741474
df.to_stata(path)
14751475

1476-
df.loc[2, "ColumnTooBig"] = np.inf
1477-
msg = (
1478-
"Column ColumnTooBig has a maximum value of infinity which is outside "
1479-
"the range supported by Stata"
1480-
)
1481-
with pytest.raises(ValueError, match=msg):
1482-
with tm.ensure_clean() as path:
1483-
df.to_stata(path)
1484-
14851476
def test_out_of_range_float(self):
14861477
original = DataFrame(
14871478
{
@@ -1507,14 +1498,17 @@ def test_out_of_range_float(self):
15071498
original["ColumnTooBig"] = original["ColumnTooBig"].astype(np.float64)
15081499
tm.assert_frame_equal(original, reread.set_index("index"))
15091500

1510-
original.loc[2, "ColumnTooBig"] = np.inf
1501+
@pytest.mark.parametrize("infval", [np.inf, -np.inf])
1502+
def test_inf(self, infval):
1503+
# GH 45350
1504+
df = DataFrame({"WithoutInf": [0.0, 1.0], "WithInf": [2.0, infval]})
15111505
msg = (
1512-
"Column ColumnTooBig has a maximum value of infinity which "
1513-
"is outside the range supported by Stata"
1506+
"Column WithInf contains infinity or -infinity"
1507+
"which is outside the range supported by Stata."
15141508
)
15151509
with pytest.raises(ValueError, match=msg):
15161510
with tm.ensure_clean() as path:
1517-
original.to_stata(path)
1511+
df.to_stata(path)
15181512

15191513
def test_path_pathlib(self):
15201514
df = tm.makeDataFrame()

0 commit comments

Comments
 (0)