Skip to content

DataFrame to dict with index orientation. #10844

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.17.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,8 @@ Other enhancements

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

- ``DataFrame.to_dict`` now accepts the *index* option in ``orient`` keyword argument (:issue:`10844`).

.. ipython :: python

s = pd.Series(['A', 'B', 'C', 'A', 'B', 'D'])
Expand Down
7 changes: 6 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ def to_dict(self, orient='dict'):

Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records'}
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
Determines the type of the values of the dictionary.

- dict (default) : dict like {column -> {index -> value}}
Expand All @@ -758,6 +758,9 @@ def to_dict(self, orient='dict'):
{index -> [index], columns -> [columns], data -> [values]}
- records : list like
[{column -> value}, ... , {column -> value}]
- index : dict like {index -> {column -> value}}

.. versionadded:: 0.17.0

Abbreviations are allowed. `s` indicates `series` and `sp`
indicates `split`.
Expand All @@ -782,6 +785,8 @@ def to_dict(self, orient='dict'):
elif orient.lower().startswith('r'):
return [dict((k, v) for k, v in zip(self.columns, row))
for row in self.values]
elif orient.lower().startswith('i'):
return dict((k, v.to_dict()) for k, v in self.iterrows())
else:
raise ValueError("orient '%s' not understood" % orient)

Expand Down
9 changes: 8 additions & 1 deletion pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4474,9 +4474,16 @@ def test_to_dict(self):

tm.assert_almost_equal(recons_data, expected_records)

# GH10844
recons_data = DataFrame(test_data).to_dict("i")

for k, v in compat.iteritems(test_data):
for k2, v2 in compat.iteritems(v):
self.assertEqual(v2, recons_data[k2][k])

def test_to_dict_invalid_orient(self):
df = DataFrame({'A':[0, 1]})
self.assertRaises(ValueError, df.to_dict, orient='invalid')
self.assertRaises(ValueError, df.to_dict, orient='xinvalid')

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