Skip to content

Commit

Permalink
BUG: to_records() fails for MultiIndex DF (pandas-dev#21064)
Browse files Browse the repository at this point in the history
  • Loading branch information
Saravia Rajal authored and Saravia Rajal committed May 16, 2018
1 parent a327920 commit 81d32b8
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.24.0.txt
Expand Up @@ -131,7 +131,7 @@ Indexing
MultiIndex
^^^^^^^^^^

-
- Bug :func:`to_records` fails for empty MultiIndex DF (:issue:`21064`)
-
-

Expand Down
8 changes: 7 additions & 1 deletion pandas/core/frame.py
Expand Up @@ -1392,7 +1392,13 @@ def to_records(self, index=True, convert_datetime64=None):
else:
if isinstance(self.index, MultiIndex):
# array of tuples to numpy cols. copy copy copy
ix_vals = lmap(np.array, zip(*self.index.values))
tuples = self.index.values
if len(tuples):
ix_vals = lmap(np.array, zip(*tuples))
else:
# empty MultiIndex DF
ix_vals = [np.array([], dtype=lev.dtype)
for lev in self.index.levels]
else:
ix_vals = [self.index.values]

Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/frame/test_convert_to.py
Expand Up @@ -328,3 +328,26 @@ 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_records_with_multiindex(self):
size = 4
tup = zip(*[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']])
index = MultiIndex.from_tuples(tup)
df = DataFrame(np.random.randn(size, size), index=index)

records = df.to_records(index=True)
assert len(records) == size
# first record includes index
assert records[0][0] == 'a'
assert records[0][1] == 'x'
# last record includes index
assert records[size - 1][0] == 'b'
assert records[size - 1][1] == 'y'

def test_to_records_with_empty_multiindex(self):
# GH 21064
multi = MultiIndex([['a'], ['b']], labels=[[], []])
df = DataFrame(columns=['A'], index=multi)

records = df.to_records(index=True)
assert len(records) == 0

0 comments on commit 81d32b8

Please sign in to comment.