Skip to content

BUG: Fix to_excel storing decimals as strings instead of numbers (issue #49598) #60230

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 3 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ MultiIndex

I/O
^^^
-
- :meth:`DataFrame.to_excel` was storing decimals as strings instead of numbers (:issue:`49598`)
-

Period
Expand Down
4 changes: 4 additions & 0 deletions pandas/io/excel/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Sequence,
)
import datetime
from decimal import Decimal
from functools import partial
import os
from textwrap import fill
Expand Down Expand Up @@ -43,6 +44,7 @@

from pandas.core.dtypes.common import (
is_bool,
is_decimal,
is_file_like,
is_float,
is_integer,
Expand Down Expand Up @@ -1348,6 +1350,8 @@ def _value_with_fmt(
val = float(val)
elif is_bool(val):
val = bool(val)
elif is_decimal(val):
val = Decimal(val)
elif isinstance(val, datetime.datetime):
fmt = self._datetime_format
elif isinstance(val, datetime.date):
Expand Down
31 changes: 31 additions & 0 deletions pandas/tests/io/excel/test_writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
datetime,
timedelta,
)
from decimal import Decimal
from functools import partial
from io import BytesIO
import os
Expand Down Expand Up @@ -977,6 +978,36 @@ def test_to_excel_float_format(self, tmp_excel):
)
tm.assert_frame_equal(result, expected)

def test_to_excel_datatypes_preserved(self, tmp_excel):
# Test that when writing and reading Excel with dtype=object,
# datatypes are preserved, except Decimals which should be
# stored as floats

# see gh-49598
df = DataFrame(
[
[1.23, "1.23", Decimal("1.23")],
[4.56, "4.56", Decimal("4.56")],
],
index=["A", "B"],
columns=["X", "Y", "Z"],
)
df.to_excel(tmp_excel)

with ExcelFile(tmp_excel) as reader:
result = pd.read_excel(reader, index_col=0, dtype=object)

expected = DataFrame(
[
[1.23, "1.23", 1.23],
[4.56, "4.56", 4.56],
],
index=["A", "B"],
columns=["X", "Y", "Z"],
dtype=object,
)
tm.assert_frame_equal(result, expected)

def test_to_excel_output_encoding(self, tmp_excel):
# Avoid mixed inferred_type.
df = DataFrame(
Expand Down