Skip to content

Commit 00dab99

Browse files
committed
[BUG-FIX] DataFrame created with tzinfo cannot use to_dict(orient="records")
Columns with datetimez are not returning arrays. Closes #18372
1 parent c4a2cd3 commit 00dab99

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v0.22.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ Bug Fixes
108108
Conversion
109109
^^^^^^^^^^
110110

111-
-
111+
- Bug in :func:`DataFrame.to_dict` where columns of datetimez were not converted to required arrays when used with ``orient='records'``, raising``TypeError` (:issue:`18372`)
112112
-
113113
-
114114

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

+16
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,16 @@ 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+
data = [(datetime(2017, 11, 18, 21, 53, 0, 219225, tzinfo=pytz.utc),),
258+
(datetime(2017, 11, 18, 22, 6, 30, 61810, tzinfo=pytz.utc,),)]
259+
df = DataFrame(list(data), columns=["d", ])
260+
261+
result = df.to_dict(orient='records')
262+
expected = [
263+
{'d': Timestamp('2017-11-18 21:53:00.219225+0000', tz=pytz.utc)},
264+
{'d': Timestamp('2017-11-18 22:06:30.061810+0000', tz=pytz.utc)},
265+
]
266+
tm.assert_dict_equal(result[0], expected[0])
267+
tm.assert_dict_equal(result[1], expected[1])

0 commit comments

Comments
 (0)