Skip to content

Commit 2181824

Browse files
Backport PR #31513: REGR: Fixed truncation with na_rep (#31542)
Co-authored-by: Tom Augspurger <[email protected]>
1 parent a8aff6c commit 2181824

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
@@ -87,6 +87,7 @@ MultiIndex
8787
I/O
8888
^^^
8989

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

pandas/core/internals/blocks.py

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

682682
if not self.is_object and not quoting and itemsize:
683-
values = values.astype(f"<U{itemsize}")
683+
values = values.astype(str)
684+
if values.dtype.itemsize / np.dtype("U1").itemsize < itemsize:
685+
# enlarge for the na_rep
686+
values = values.astype(f"<U{itemsize}")
684687
else:
685688
values = np.array(values, dtype="object")
686689

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)