Skip to content

BUG: HDFStore select for large integer #54186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jul 19, 2023
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ Conversion
- Bug in :meth:`DataFrame.__repr__` incorrectly raising a ``TypeError`` when the dtype of a column is ``np.record`` (:issue:`48526`)
- Bug in :meth:`DataFrame.info` raising ``ValueError`` when ``use_numba`` is set (:issue:`51922`)
- Bug in :meth:`DataFrame.insert` raising ``TypeError`` if ``loc`` is ``np.int64`` (:issue:`53193`)
-
- Bug in :meth:`HDFStore.select` loses precision of large int when stored and retrieved (:issue:`54186`)

Strings
^^^^^^^
Expand Down
11 changes: 10 additions & 1 deletion pandas/core/computation/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,16 @@ def stringify(value):
result = metadata.searchsorted(v, side="left")
return TermValue(result, result, "integer")
elif kind == "integer":
v = int(float(v))
from decimal import (
Decimal,
InvalidOperation,
)

try:
v_dec = Decimal(v)
v = int(v_dec.to_integral_exact(rounding="ROUND_HALF_EVEN"))
except InvalidOperation:
raise ValueError("could not convert string to ")
return TermValue(v, v, kind)
elif kind == "float":
v = float(v)
Expand Down
21 changes: 20 additions & 1 deletion pandas/tests/io/pytables/test_select.py
Original file line number Diff line number Diff line change
Expand Up @@ -914,7 +914,7 @@ def test_query_compare_column_type(setup_path):
if col == "real_date":
msg = 'Given date string "a" not likely a datetime'
else:
msg = "could not convert string to "
msg = "could not convert string to"
with pytest.raises(ValueError, match=msg):
store.select("test", where=query)

Expand Down Expand Up @@ -943,3 +943,22 @@ def test_select_empty_where(tmp_path, where):
store.put("df", df, "t")
result = read_hdf(store, "df", where=where)
tm.assert_frame_equal(result, df)


def test_select_large_integer(tmp_path):
path = tmp_path / "large_int.h5"

df = DataFrame(
zip(
["a", "b", "c", "d"],
[-9223372036854775801, -9223372036854775802, -9223372036854775803, 123],
),
columns=["x", "y"],
)
result = None
with HDFStore(path) as s:
s.append("data", df, data_columns=True, index=False)
result = s.select("data", where="y==-9223372036854775801").get("y").get(0)
expected = df["y"][0]

assert expected == result