Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 2 additions & 2 deletions doc/source/whatsnew/v0.24.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ Bug Fixes

**Conversion**

-
-
- Bug in :meth:`DataFrame.itertuples` with ``records`` orient raising an AttributeError when the ``DataFrame`` contained more than 255 columns (:issue:`24939`)
- Bug in :meth:`DataFrame.itertuples` orient converting integer column names to strings prepended with an underscore (:issue:`24940`)
-

**Indexing**
Expand Down
7 changes: 5 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1296,10 +1296,13 @@ def to_dict(self, orient='dict', into=dict):
return into_c((k, com.maybe_box_datetimelike(v))
for k, v in compat.iteritems(self))
elif orient.lower().startswith('r'):
columns = self.columns.tolist()
rows = (dict(zip(columns, row))
for row in self.itertuples(index=False))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can use name=None here to avoid creating namedtuples (we don't need them, and it's a bit faster to generate plain tuples)

return [
into_c((k, com.maybe_box_datetimelike(v))
for k, v in compat.iteritems(row._asdict()))
for row in self.itertuples(index=False)]
for k, v in compat.iteritems(row))
for row in rows]
elif orient.lower().startswith('i'):
if not self.index.is_unique:
raise ValueError(
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/frame/test_convert_to.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,3 +488,17 @@ def test_to_dict_index_dtypes(self, into, expected):
result = DataFrame.from_dict(result, orient='index')[cols]
expected = DataFrame.from_dict(expected, orient='index')[cols]
tm.assert_frame_equal(result, expected)

def test_to_dict_numeric_names(self):
# https://github.com/pandas-dev/pandas/issues/24940
df = DataFrame({str(i): [i] for i in range(5)})
result = set(df.to_dict('records')[0].keys())
expected = set(df.columns)
assert result == expected

def test_to_dict_wide(self):
# https://github.com/pandas-dev/pandas/issues/24939
df = DataFrame({('A_%d' % i): [i] for i in range(256)})
result = df.to_dict('records')[0]
expected = {'A_{:d}'.format(i): i for i in range(256)}
assert result == expected