Skip to content

Commit 2c5b458

Browse files
committed
Merge pull request #10845 from soupault/timedelta-bugfix
BUG: Error while saving DataFrame with TimedeltaIndex to .csv #10833
2 parents a6ee127 + 2093cc5 commit 2c5b458

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v0.17.0.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,3 +761,4 @@ Bug Fixes
761761
- Bug in ``iloc`` allowing memory outside bounds of a Series to be accessed with negative integers (:issue:`10779`)
762762
- Bug in ``read_msgpack`` where encoding is not respected (:issue:`10580`)
763763
- Bug preventing access to the first index when using ``iloc`` with a list containing the appropriate negative integer (:issue:`10547`, :issue:`10779`)
764+
- Bug in ``TimedeltaIndex`` formatter causing error while trying to save ``DataFrame`` with ``TimedeltaIndex`` using ``to_csv`` (:issue:`10833`)

pandas/core/format.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2190,7 +2190,7 @@ def __init__(self, values, nat_rep='NaT', box=False, **kwargs):
21902190
def _format_strings(self):
21912191
formatter = self.formatter or _get_format_timedelta64(self.values, nat_rep=self.nat_rep,
21922192
box=self.box)
2193-
fmt_values = [formatter(x) for x in self.values]
2193+
fmt_values = np.array([formatter(x) for x in self.values])
21942194
return fmt_values
21952195

21962196

pandas/tests/test_frame.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6312,7 +6312,6 @@ def test_to_csv_from_csv(self):
63126312
header=['AA', 'X'])
63136313

63146314
with ensure_clean(pname) as path:
6315-
import pandas as pd
63166315
df1 = DataFrame(np.random.randn(3, 1))
63176316
df2 = DataFrame(np.random.randn(3, 1))
63186317

@@ -6324,6 +6323,22 @@ def test_to_csv_from_csv(self):
63246323
xp.columns = lmap(int,xp.columns)
63256324
assert_frame_equal(xp,rs)
63266325

6326+
with ensure_clean() as path:
6327+
# GH 10833 (TimedeltaIndex formatting)
6328+
dt = pd.Timedelta(seconds=1)
6329+
df = pd.DataFrame({'dt_data': [i*dt for i in range(3)]},
6330+
index=pd.Index([i*dt for i in range(3)],
6331+
name='dt_index'))
6332+
df.to_csv(path)
6333+
6334+
result = pd.read_csv(path, index_col='dt_index')
6335+
result.index = pd.to_timedelta(result.index)
6336+
# TODO: remove renaming when GH 10875 is solved
6337+
result.index = result.index.rename('dt_index')
6338+
result['dt_data'] = pd.to_timedelta(result['dt_data'])
6339+
6340+
assert_frame_equal(df, result, check_index_type=True)
6341+
63276342
def test_to_csv_cols_reordering(self):
63286343
# GH3454
63296344
import pandas as pd

0 commit comments

Comments
 (0)