Skip to content

Commit f393d18

Browse files
committed
Fix pandas-dev#25099 set na_rep values before converting to string to prevent data truncation
1 parent f75a220 commit f393d18

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

pandas/core/internals/blocks.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,10 @@ def to_native_types(self, slicer=None, na_rep='nan', quoting=None,
739739
mask = isna(values)
740740

741741
if not self.is_object and not quoting:
742-
values = values.astype(str)
742+
if na_rep and isinstance(na_rep, str):
743+
values = values.astype("<U{length}".format(length=len(na_rep)))
744+
else:
745+
values = values.astype(str)
743746
else:
744747
values = np.array(values, dtype='object')
745748

pandas/tests/io/formats/test_to_csv.py

+16
Original file line numberDiff line numberDiff line change
@@ -561,3 +561,19 @@ def test_to_csv_compression(self, compression_only,
561561
result = pd.read_csv(path, index_col=0,
562562
compression=read_compression)
563563
tm.assert_frame_equal(result, df)
564+
565+
def test_to_csv_na_rep_long_string(self, capsys):
566+
# see gh-25099
567+
df = pd.DataFrame({"c": [float('nan')] * 3})
568+
df = df.astype("Int64")
569+
expected_rows = ['c',
570+
'mynull',
571+
'mynull',
572+
'mynull']
573+
expected_ascii = tm.convert_rows_list_to_csv_str(expected_rows)
574+
575+
df.to_csv(sys.stdout, index=False, na_rep='mynull', encoding='ascii')
576+
captured = capsys.readouterr()
577+
578+
assert captured.out == expected_ascii
579+
assert not sys.stdout.closed

0 commit comments

Comments
 (0)