diff --git a/doc/source/release.rst b/doc/source/release.rst index 769b47b18db08..f6afea583762b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -47,6 +47,8 @@ pandas 0.13 - Added a more informative error message when plot arguments contain overlapping color and style arguments (:issue:`4402`) - Significant table writing performance improvements in ``HDFStore`` + - ``to_dict`` now takes ``records`` as a possible outtype. Returns an array + of column-keyed dictionaries. (:pullrequest:`4936`) **API Changes** diff --git a/doc/source/v0.13.0.txt b/doc/source/v0.13.0.txt index 7da2f03ad4c74..b74de1c7be17b 100644 --- a/doc/source/v0.13.0.txt +++ b/doc/source/v0.13.0.txt @@ -81,6 +81,8 @@ Enhancements - Clipboard functionality now works with PySide (:issue:`4282`) - Added a more informative error message when plot arguments contain overlapping color and style arguments (:issue:`4402`) + - ``to_dict`` now takes ``records`` as a possible outtype. Returns an array + of column-keyed dictionaries. (:pullrequest:`4936`) Bug Fixes ~~~~~~~~~ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0f3bcb32f7287..c0e868f27345c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -962,11 +962,11 @@ def to_dict(self, outtype='dict'): Parameters ---------- - outtype : str {'dict', 'list', 'series'} + outtype : str {'dict', 'list', 'series', 'records'} Determines the type of the values of the dictionary. The default `dict` is a nested dictionary {column -> {index -> value}}. `list` returns {column -> list(values)}. `series` returns - {column -> Series(values)}. + {column -> Series(values)}. `records` returns [{columns -> value}]. Abbreviations are allowed. @@ -983,6 +983,9 @@ def to_dict(self, outtype='dict'): return dict((k, v.tolist()) for k, v in compat.iteritems(self)) elif outtype.lower().startswith('s'): return dict((k, v) for k, v in compat.iteritems(self)) + elif outtype.lower().startswith('r'): + return [dict((k, v) for k, v in zip(self.columns, row)) \ + for row in self.values] else: # pragma: no cover raise ValueError("outtype %s not understood" % outtype) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 1b405eae08797..c5ecba3555784 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -3396,6 +3396,14 @@ def test_to_dict(self): for k2, v2 in compat.iteritems(v): self.assertEqual(v2, recons_data[k][k2]) + recons_data = DataFrame(test_data).to_dict("r") + + expected_records = [{'A': 1.0, 'B': '1'}, + {'A': 2.0, 'B': '2'}, + {'A': nan, 'B': '3'}] + + tm.assert_almost_equal(recons_data, expected_records) + def test_to_records_dt64(self): df = DataFrame([["one", "two", "three"], ["four", "five", "six"]],