Skip to content

Changing columns with += gives UnboundLocalError #4996

Closed
@wcbeard

Description

@wcbeard
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: np.random.seed(10)
In [4]: a = np.random.randint(0, 20, (6, 5))
In [5]: df = pd.DataFrame(a, columns=list('abcde'))
In [6]: df
Out[6]:
    a   b   c   d   e
0   9   4  15   0  17
1  16  17   8   9   0
2  10   8   4  19  16
3   4  15  11  11   1
4   8   4  14  17  19
5  13   5  13  19  13

Changing columns with + is fine

In [7]: df.columns = df.columns + '_x'
In [8]: df
Out[8]:
   a_x  b_x  c_x  d_x  e_x
0    9    4   15    0   17
1   16   17    8    9    0
2   10    8    4   19   16
3    4   15   11   11    1
4    8    4   14   17   19
5   13    5   13   19   13

The += operator on the other hand correctly changes the columns,

In [9]: df.columns += '_y'
In [10]: df.columns
Out[10]: Index([u'a_x_y', u'b_x_y', u'c_x_y', u'd_x_y', u'e_x_y'], dtype=object)

but gives an error when trying to display the whole dataframe:

In [11]: df
Out[11]: ---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)

Traceback is here. Not sure if it's an ipython or pandas issue. pd.__version__ == '0.12.0-371-g1434776'

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugIndexingRelated to indexing on series/frames, not to indexes themselves

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions