Skip to content

Commit ccd3186

Browse files
committed
Fix issue with to_csv na_rep when dtype=string
1 parent facd756 commit ccd3186

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

pandas/core/internals/blocks.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1774,8 +1774,8 @@ def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs):
17741774
mask = isna(values)
17751775

17761776
try:
1777-
values = values.astype(str)
17781777
values[mask] = na_rep
1778+
values = values.astype(str)
17791779
except Exception:
17801780
# eg SparseArray does not support setitem, needs to be converted to ndarray
17811781
return super().to_native_types(slicer, na_rep, quoting, **kwargs)

pandas/tests/io/formats/test_to_csv.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,14 @@ def test_to_csv_na_rep(self):
204204
assert df.set_index("a").to_csv(na_rep="_") == expected
205205
assert df.set_index(["a", "b"]).to_csv(na_rep="_") == expected
206206

207+
# GH 29975
208+
# Make sure full na_rep shows up when a dtype is provided
209+
csv = pd.Series(["a", pd.NA, "c"]).to_csv(na_rep="ZZZZZ")
210+
assert ",0\n0,a\n1,ZZZZZ\n2,c\n" == csv
211+
212+
csv = pd.Series(["a", pd.NA, "c"], dtype="string").to_csv(na_rep="ZZZZZ")
213+
assert ",0\n0,a\n1,ZZZZZ\n2,c\n" == csv
214+
207215
def test_to_csv_date_format(self):
208216
# GH 10209
209217
df_sec = DataFrame({"A": pd.date_range("20130101", periods=5, freq="s")})

0 commit comments

Comments
 (0)