Skip to content

Commit ca6475d

Browse files
committed
Add 'records' outtype to to_dict method.
1 parent e9db624 commit ca6475d

File tree

4 files changed

+17
-2
lines changed

4 files changed

+17
-2
lines changed

doc/source/release.rst

+2
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ pandas 0.13
4747
- Added a more informative error message when plot arguments contain
4848
overlapping color and style arguments (:issue:`4402`)
4949
- Significant table writing performance improvements in ``HDFStore``
50+
- ``to_dict`` now takes ``records`` as a possible outtype. Returns an array
51+
of column-keyed dictionaries. (:pullrequest:`4936`)
5052

5153
**API Changes**
5254

doc/source/v0.13.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ Enhancements
8181
- Clipboard functionality now works with PySide (:issue:`4282`)
8282
- Added a more informative error message when plot arguments contain
8383
overlapping color and style arguments (:issue:`4402`)
84+
- ``to_dict`` now takes ``records`` as a possible outtype. Returns an array
85+
of column-keyed dictionaries. (:pullrequest:`4936`)
8486

8587
Bug Fixes
8688
~~~~~~~~~

pandas/core/frame.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -962,11 +962,11 @@ def to_dict(self, outtype='dict'):
962962
963963
Parameters
964964
----------
965-
outtype : str {'dict', 'list', 'series'}
965+
outtype : str {'dict', 'list', 'series', 'records'}
966966
Determines the type of the values of the dictionary. The
967967
default `dict` is a nested dictionary {column -> {index -> value}}.
968968
`list` returns {column -> list(values)}. `series` returns
969-
{column -> Series(values)}.
969+
{column -> Series(values)}. `records` returns [{columns -> value}].
970970
Abbreviations are allowed.
971971
972972
@@ -983,6 +983,9 @@ def to_dict(self, outtype='dict'):
983983
return dict((k, v.tolist()) for k, v in compat.iteritems(self))
984984
elif outtype.lower().startswith('s'):
985985
return dict((k, v) for k, v in compat.iteritems(self))
986+
elif outtype.lower().startswith('r'):
987+
return [dict((k, v) for k, v in zip(self.columns, row)) \
988+
for row in self.values]
986989
else: # pragma: no cover
987990
raise ValueError("outtype %s not understood" % outtype)
988991

pandas/tests/test_frame.py

+8
Original file line numberDiff line numberDiff line change
@@ -3396,6 +3396,14 @@ def test_to_dict(self):
33963396
for k2, v2 in compat.iteritems(v):
33973397
self.assertEqual(v2, recons_data[k][k2])
33983398

3399+
recons_data = DataFrame(test_data).to_dict("r")
3400+
3401+
expected_records = [{'A': 1.0, 'B': '1'},
3402+
{'A': 2.0, 'B': '2'},
3403+
{'A': nan, 'B': '3'}]
3404+
3405+
tm.assert_almost_equal(recons_data, expected_records)
3406+
33993407
def test_to_records_dt64(self):
34003408
df = DataFrame([["one", "two", "three"],
34013409
["four", "five", "six"]],

0 commit comments

Comments
 (0)