Skip to content

Commit 809197f

Browse files
committed
Fixed itertuples usage in to_dict
Closes pandas-dev#24940 Closes pandas-dev#24939
1 parent 2b16e2e commit 809197f

File tree

3 files changed

+21
-4
lines changed

3 files changed

+21
-4
lines changed

doc/source/whatsnew/v0.24.1.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ Bug Fixes
2929

3030
**Conversion**
3131

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

3636
**Indexing**

pandas/core/frame.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1296,10 +1296,13 @@ def to_dict(self, orient='dict', into=dict):
12961296
return into_c((k, com.maybe_box_datetimelike(v))
12971297
for k, v in compat.iteritems(self))
12981298
elif orient.lower().startswith('r'):
1299+
columns = self.columns.tolist()
1300+
rows = (dict(zip(columns, row))
1301+
for row in self.itertuples(index=False))
12991302
return [
13001303
into_c((k, com.maybe_box_datetimelike(v))
1301-
for k, v in compat.iteritems(row._asdict()))
1302-
for row in self.itertuples(index=False)]
1304+
for k, v in compat.iteritems(row))
1305+
for row in rows]
13031306
elif orient.lower().startswith('i'):
13041307
if not self.index.is_unique:
13051308
raise ValueError(

pandas/tests/frame/test_convert_to.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,3 +488,17 @@ def test_to_dict_index_dtypes(self, into, expected):
488488
result = DataFrame.from_dict(result, orient='index')[cols]
489489
expected = DataFrame.from_dict(expected, orient='index')[cols]
490490
tm.assert_frame_equal(result, expected)
491+
492+
def test_to_dict_numeric_names(self):
493+
# https://github.com/pandas-dev/pandas/issues/24940
494+
df = DataFrame({str(i): [i] for i in range(5)})
495+
result = set(df.to_dict('records')[0].keys())
496+
expected = set(df.columns)
497+
assert result == expected
498+
499+
def test_to_dict_wide(self):
500+
# https://github.com/pandas-dev/pandas/issues/24939
501+
df = DataFrame({('A_%d' % i): [i] for i in range(256)})
502+
result = df.to_dict('records')[0]
503+
expected = {'A_{:d}'.format(i): i for i in range(256)}
504+
assert result == expected

0 commit comments

Comments
 (0)