Skip to content

Commit 4e09480

Browse files
bolkedebruinjreback
authored andcommitted
[BUG-FIX] DataFrame created with tzinfo cannot use to_dict(orient="records") (#18416)
Closes #18372
1 parent 6c074d1 commit 4e09480

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

doc/source/whatsnew/v0.21.1.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ Conversion
6363
- Bug in :class:`TimedeltaIndex` subtraction could incorrectly overflow when ``NaT`` is present (:issue:`17791`)
6464
- Bug in :class:`DatetimeIndex` subtracting datetimelike from DatetimeIndex could fail to overflow (:issue:`18020`)
6565
- Bug in :meth:`IntervalIndex.copy` when copying and ``IntervalIndex`` with non-default ``closed`` (:issue:`18339`)
66-
-
66+
- Bug in :func:`DataFrame.to_dict` where columns of datetime that are tz-aware were not converted to required arrays when used with ``orient='records'``, raising``TypeError` (:issue:`18372`)
6767
-
6868
-
6969

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -993,7 +993,7 @@ def to_dict(self, orient='dict', into=dict):
993993
for k, v in compat.iteritems(self))
994994
elif orient.lower().startswith('r'):
995995
return [into_c((k, _maybe_box_datetimelike(v))
996-
for k, v in zip(self.columns, row))
996+
for k, v in zip(self.columns, np.atleast_1d(row)))
997997
for row in self.values]
998998
elif orient.lower().startswith('i'):
999999
return into_c((k, v.to_dict(into)) for k, v in self.iterrows())

pandas/tests/frame/test_convert_to.py

+18
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
# -*- coding: utf-8 -*-
22

3+
from datetime import datetime
4+
35
import pytest
6+
import pytz
47
import collections
58
import numpy as np
69

@@ -249,3 +252,18 @@ def test_to_dict_box_scalars(self):
249252

250253
result = DataFrame(d).to_dict(orient='records')
251254
assert isinstance(result[0]['a'], (int, long))
255+
256+
def test_frame_to_dict_tz(self):
257+
# GH18372 When converting to dict with orient='records' columns of
258+
# datetime that are tz-aware were not converted to required arrays
259+
data = [(datetime(2017, 11, 18, 21, 53, 0, 219225, tzinfo=pytz.utc),),
260+
(datetime(2017, 11, 18, 22, 6, 30, 61810, tzinfo=pytz.utc,),)]
261+
df = DataFrame(list(data), columns=["d", ])
262+
263+
result = df.to_dict(orient='records')
264+
expected = [
265+
{'d': Timestamp('2017-11-18 21:53:00.219225+0000', tz=pytz.utc)},
266+
{'d': Timestamp('2017-11-18 22:06:30.061810+0000', tz=pytz.utc)},
267+
]
268+
tm.assert_dict_equal(result[0], expected[0])
269+
tm.assert_dict_equal(result[1], expected[1])

0 commit comments

Comments
 (0)