Skip to content

Commit 08895fa

Browse files
REGR: Fixed truncation with na_rep (pandas-dev#31513)
1 parent bfb80fa commit 08895fa

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

doc/source/whatsnew/v1.0.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ MultiIndex
8989
I/O
9090
^^^
9191

92+
- Fixed regression in :meth:`~DataFrame.to_csv` where specifying an ``na_rep`` might truncate the values written (:issue:`31447`)
9293
-
9394
-
9495

pandas/core/internals/blocks.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,10 @@ def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs):
684684
itemsize = writers.word_len(na_rep)
685685

686686
if not self.is_object and not quoting and itemsize:
687-
values = values.astype(f"<U{itemsize}")
687+
values = values.astype(str)
688+
if values.dtype.itemsize / np.dtype("U1").itemsize < itemsize:
689+
# enlarge for the na_rep
690+
values = values.astype(f"<U{itemsize}")
688691
else:
689692
values = np.array(values, dtype="object")
690693

pandas/tests/io/formats/test_to_csv.py

+14
Original file line numberDiff line numberDiff line change
@@ -583,3 +583,17 @@ def test_to_csv_timedelta_precision(self):
583583
]
584584
expected = tm.convert_rows_list_to_csv_str(expected_rows)
585585
assert result == expected
586+
587+
def test_na_rep_truncated(self):
588+
# https://github.com/pandas-dev/pandas/issues/31447
589+
result = pd.Series(range(8, 12)).to_csv(na_rep="-")
590+
expected = tm.convert_rows_list_to_csv_str([",0", "0,8", "1,9", "2,10", "3,11"])
591+
assert result == expected
592+
593+
result = pd.Series([True, False]).to_csv(na_rep="nan")
594+
expected = tm.convert_rows_list_to_csv_str([",0", "0,True", "1,False"])
595+
assert result == expected
596+
597+
result = pd.Series([1.1, 2.2]).to_csv(na_rep=".")
598+
expected = tm.convert_rows_list_to_csv_str([",0", "0,1.1", "1,2.2"])
599+
assert result == expected

0 commit comments

Comments
 (0)