Skip to content

Commit 5245859

Browse files
kinowBruno P. Kinoshita
authored and
Bruno P. Kinoshita
committed
Fix #25099 set na_rep values before converting to string to prevent data truncation
1 parent d3c9d6e commit 5245859

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-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

+17
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import pandas as pd
1010
from pandas import DataFrame, compat
11+
from pandas.compat import StringIO
1112
from pandas.util import testing as tm
1213

1314

@@ -561,3 +562,19 @@ def test_to_csv_compression(self, compression_only,
561562
result = pd.read_csv(path, index_col=0,
562563
compression=read_compression)
563564
tm.assert_frame_equal(result, df)
565+
566+
def test_to_csv_na_rep_long_string(self, capsys):
567+
# see gh-25099
568+
df = pd.DataFrame({"c": [float('nan')] * 3})
569+
df = df.astype("Int64")
570+
expected_rows = ['c',
571+
'mynull',
572+
'mynull',
573+
'mynull']
574+
expected = tm.convert_rows_list_to_csv_str(expected_rows)
575+
576+
csv_output = StringIO()
577+
df.to_csv(csv_output, index=False, na_rep='mynull', encoding='ascii')
578+
result = csv_output.getvalue()
579+
580+
assert result == expected

0 commit comments

Comments
 (0)