Skip to content

Commit

Permalink
BUG: to_records() fails for MultiIndex DF (#21064)
Browse files Browse the repository at this point in the history
  • Loading branch information
Saravia Rajal authored and Saravia Rajal committed May 23, 2018
1 parent a327920 commit f89e883
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
32 changes: 32 additions & 0 deletions pandas/tests/frame/test_convert_to.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,3 +328,35 @@ 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
idx1 = [u'a', u'a', u'b', u'b']
idx2 = [u'x', u'y', u'x', u'y']
tup = zip(idx1, idx2)
index = MultiIndex.from_tuples(tup)
random_data = np.random.randn(size, size)
df = DataFrame(random_data, index=index)

result = df.to_records(index=True)

col_arrays = [idx1, idx2] + [col for col in random_data.T]
expected = np.rec.fromarrays(
col_arrays, dtype=np.dtype([('level_0', '<U1'), ('level_1', '<U1'),
('0', '<f8'), ('1', '<f8'),
('2', '<f8'), ('3', '<f8')]))

tm.assert_numpy_array_equal(result, expected)

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

expected = np.rec.fromarrays([[], [], []],
dtype=np.dtype([('level_0', 'O'),
('level_1', 'O'),
('A', 'O')]))

result = df.to_records(index=True)
tm.assert_numpy_array_equal(result, expected)

0 comments on commit f89e883

Please sign in to comment.