pydata/pandas — pull request #5429 by jmcnamara (2013-11-04 01:38:29+00:00)
Title: BUG: Excel writer doesn't handle "cols" option correctly

Issue #5427

Notes on this PR:

* This fix addresses an issue introduced in #5235 (Issue with Excel writers when column names are duplicated).
* Basically it needs to handle 2 different use cases:
* The user uses duplicate column names
* The user specifies a different order via the `cols` option

```python
# Case 1
df = pd.DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]])

df.columns = ['A', 'B', 'B']
```

```python
# Case 2
df = pd.DataFrame({'A': ['a', 'a', 'a'],
'B': ['b', 'b', 'b']})

df.to_excel('frame.xlsx', sheet_name='Sheet1', cols=['B', 'A'])

```

The proposed solution is to iterate through self.columns in the default or user supplied order. If a duplicate column name is encountered (i.e. if `df['B']` returns more than one series) then we select the first series and keep track of that index. If the duplicate column name is encountered again then we select the next available series from `df['B']` up to the last series available. If the duplicate name is encountered again then we return the last series again.

The patch is slightly kludgy. I didn't know how to check if `df[col]` contained more than one series so I used `len(self.df[col_name].columns)` in a `try:catch`. Hopefully there is something cleaner.

The change is repeated twice in the code.

There is a new test for this issue and an existing test for the previous issue.

I don't think this needs a release note since it is a fix for an issue that was never released.