Skip to content

Commit 5d941df

Browse files
committed
Fix pandas-dev#25099 set na_rep values before converting to string to prevent data truncation
1 parent 2769ebf commit 5d941df

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
@@ -723,7 +723,10 @@ def to_native_types(self, slicer=None, na_rep='nan', quoting=None,
723723
mask = isna(values)
724724

725725
if not self.is_object and not quoting:
726-
values = values.astype(str)
726+
if na_rep and isinstance(na_rep, str):
727+
values = values.astype("<U{length}".format(length=len(na_rep)))
728+
else:
729+
values = values.astype(str)
727730
else:
728731
values = np.array(values, dtype='object')
729732

pandas/tests/io/formats/test_to_csv.py

+16
Original file line numberDiff line numberDiff line change
@@ -537,3 +537,19 @@ def test_to_csv_compression(self, compression_only,
537537
result = pd.read_csv(path, index_col=0,
538538
compression=read_compression)
539539
tm.assert_frame_equal(result, df)
540+
541+
def test_to_csv_na_rep_long_string(self, capsys):
542+
# see gh-25099
543+
df = pd.DataFrame({"c": [float('nan')] * 3})
544+
df = df.astype("Int64")
545+
expected_rows = ['c',
546+
'mynull',
547+
'mynull',
548+
'mynull']
549+
expected_ascii = tm.convert_rows_list_to_csv_str(expected_rows)
550+
551+
df.to_csv(sys.stdout, index=False, na_rep='mynull', encoding='ascii')
552+
captured = capsys.readouterr()
553+
554+
assert captured.out == expected_ascii
555+
assert not sys.stdout.closed

0 commit comments

Comments
 (0)