Skip to content

Commit 6f31f8c

Browse files
committed
ENH: allow to_csv to save nans and infs
1 parent b941968 commit 6f31f8c

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

pandas/core/frame.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1105,7 +1105,9 @@ def _helper_csvexcel(self, writer, na_rep=None, cols=None,
11051105
for i, col in enumerate(cols):
11061106
val = series[col][j]
11071107
if lib.checknull(val):
1108-
val = na_rep
1108+
# HACK: special-case option for including nan, inf, -inf in csv
1109+
if na_rep != 'nans_and_infs':
1110+
val = na_rep
11091111

11101112
if float_format is not None and com.is_float(val):
11111113
val = float_format % val

pandas/tests/test_frame.py

+17-4
Original file line numberDiff line numberDiff line change
@@ -3382,16 +3382,29 @@ def test_to_csv_from_csv(self):
33823382

33833383
os.remove(path)
33843384

3385-
def test_to_csv_from_csv_w_infs(self):
3385+
def test_to_csv_from_csv_w_some_infs(self):
33863386
path = '__tmp__'
33873387

33883388
# test roundtrip with inf, -inf, nan, as full columns and mix
3389-
self.frame['E'] = np.inf
3390-
self.frame['F'] = -np.inf
33913389
self.frame['G'] = np.nan
33923390
self.frame['H'] = self.frame.index.map(lambda x: [np.inf, np.nan][np.random.rand() < .5])
33933391

3394-
self.frame.to_csv(path)
3392+
self.frame.to_csv(path, na_rep='nans_and_infs')
3393+
recons = DataFrame.from_csv(path)
3394+
3395+
assert_frame_equal(self.frame, recons)
3396+
assert_frame_equal(np.isinf(self.frame), np.isinf(recons))
3397+
3398+
os.remove(path)
3399+
3400+
def test_to_csv_from_csv_w_all_infs(self):
3401+
path = '__tmp__'
3402+
3403+
# test roundtrip with inf, -inf, nan, as full columns and mix
3404+
self.frame['E'] = np.inf
3405+
self.frame['F'] = -np.inf
3406+
3407+
self.frame.to_csv(path, na_rep='nans_and_infs')
33953408
recons = DataFrame.from_csv(path)
33963409

33973410
assert_frame_equal(self.frame, recons)

0 commit comments

Comments
 (0)