Skip to content

Commit

Permalink
Merge pull request pandas-dev#5429 from jmcnamara/bug_excel_cols_option
Browse files Browse the repository at this point in the history
BUG: Excel writer doesn't handle "cols" option correctly
  • Loading branch information
jtratner committed Nov 6, 2013
2 parents 3c57949 + 96134ba commit 80d8a7a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
12 changes: 10 additions & 2 deletions pandas/core/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1393,8 +1393,12 @@ def _format_regular_rows(self):
for idx, idxval in enumerate(index_values):
yield ExcelCell(self.rowcounter + idx, 0, idxval, header_style)

# Get a frame that will account for any duplicates in the column names.
col_mapped_frame = self.df.loc[:, self.columns]

# Write the body of the frame data series by series.
for colidx in range(len(self.columns)):
series = self.df.iloc[:, colidx]
series = col_mapped_frame.iloc[:, colidx]
for i, val in enumerate(series):
yield ExcelCell(self.rowcounter + i, colidx + coloffset, val)

Expand Down Expand Up @@ -1461,8 +1465,12 @@ def _format_hierarchical_rows(self):
header_style)
gcolidx += 1

# Get a frame that will account for any duplicates in the column names.
col_mapped_frame = self.df.loc[:, self.columns]

# Write the body of the frame data series by series.
for colidx in range(len(self.columns)):
series = self.df.iloc[:, colidx]
series = col_mapped_frame.iloc[:, colidx]
for i, val in enumerate(series):
yield ExcelCell(self.rowcounter + i, gcolidx + colidx, val)

Expand Down
16 changes: 15 additions & 1 deletion pandas/io/tests/test_excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -922,11 +922,25 @@ def test_duplicated_columns(self):
write_frame.columns = colnames
write_frame.to_excel(path, 'test1')

read_frame = read_excel(path, 'test1').astype(np.int64)
read_frame = read_excel(path, 'test1')
read_frame.columns = colnames

tm.assert_frame_equal(write_frame, read_frame)

def test_swapped_columns(self):
# Test for issue #5427.
_skip_if_no_xlrd()

with ensure_clean(self.ext) as path:
write_frame = DataFrame({'A': [1, 1, 1],
'B': [2, 2, 2]})
write_frame.to_excel(path, 'test1', cols=['B', 'A'])

read_frame = read_excel(path, 'test1', header=0)

tm.assert_series_equal(write_frame['A'], read_frame['A'])
tm.assert_series_equal(write_frame['B'], read_frame['B'])


class OpenpyxlTests(ExcelWriterBase, unittest.TestCase):
ext = '.xlsx'
Expand Down

0 comments on commit 80d8a7a

Please sign in to comment.