Skip to content

Commit 73dcb95

Browse files
gabrielaraujofjreback
authored andcommitted
ENH: Index orientation option when converting a DataFrame into a dict, #10844
Added an index orient option for DataFrame.to_dict method. Updated tests with index option.
1 parent 2c5b458 commit 73dcb95

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

doc/source/whatsnew/v0.17.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,8 @@ Other enhancements
175175

176176
- ``msgpack`` submodule has been updated to 0.4.6 with backward compatibility (:issue:`10581`)
177177

178+
- ``DataFrame.to_dict`` now accepts the *index* option in ``orient`` keyword argument (:issue:`10844`).
179+
178180
.. ipython :: python
179181

180182
s = pd.Series(['A', 'B', 'C', 'A', 'B', 'D'])

pandas/core/frame.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -747,7 +747,7 @@ def to_dict(self, orient='dict'):
747747
748748
Parameters
749749
----------
750-
orient : str {'dict', 'list', 'series', 'split', 'records'}
750+
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
751751
Determines the type of the values of the dictionary.
752752
753753
- dict (default) : dict like {column -> {index -> value}}
@@ -757,6 +757,9 @@ def to_dict(self, orient='dict'):
757757
{index -> [index], columns -> [columns], data -> [values]}
758758
- records : list like
759759
[{column -> value}, ... , {column -> value}]
760+
- index : dict like {index -> {column -> value}}
761+
762+
.. versionadded:: 0.17.0
760763
761764
Abbreviations are allowed. `s` indicates `series` and `sp`
762765
indicates `split`.
@@ -781,6 +784,8 @@ def to_dict(self, orient='dict'):
781784
elif orient.lower().startswith('r'):
782785
return [dict((k, v) for k, v in zip(self.columns, row))
783786
for row in self.values]
787+
elif orient.lower().startswith('i'):
788+
return dict((k, v.to_dict()) for k, v in self.iterrows())
784789
else:
785790
raise ValueError("orient '%s' not understood" % orient)
786791

pandas/tests/test_frame.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -4467,9 +4467,16 @@ def test_to_dict(self):
44674467

44684468
tm.assert_almost_equal(recons_data, expected_records)
44694469

4470+
# GH10844
4471+
recons_data = DataFrame(test_data).to_dict("i")
4472+
4473+
for k, v in compat.iteritems(test_data):
4474+
for k2, v2 in compat.iteritems(v):
4475+
self.assertEqual(v2, recons_data[k2][k])
4476+
44704477
def test_to_dict_invalid_orient(self):
44714478
df = DataFrame({'A':[0, 1]})
4472-
self.assertRaises(ValueError, df.to_dict, orient='invalid')
4479+
self.assertRaises(ValueError, df.to_dict, orient='xinvalid')
44734480

44744481
def test_to_records_dt64(self):
44754482
df = DataFrame([["one", "two", "three"],

0 commit comments

Comments
 (0)