Skip to content

Commit

Permalink
ENH: can set existing columns via attributes as convenience, close #883
Browse files Browse the repository at this point in the history
  • Loading branch information
wesm committed Mar 13, 2012
1 parent 387ec4d commit 7e4b086
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1479,6 +1479,23 @@ def __getattr__(self, name):
raise AttributeError("'%s' object has no attribute '%s'" %
(type(self).__name__, name))

def __setattr__(self, name, value):
"""After regular attribute access, try looking up the name of a column.
This allows simpler access to columns for interactive use."""
if name == '_data':
super(DataFrame, self).__setattr__(name, value)
else:
try:
existing = getattr(self, name)
if isinstance(existing, Index):
super(DataFrame, self).__setattr__(name, value)
elif name in self.columns:
self[name] = value
else:
object.__setattr__(self, name, value)
except (AttributeError, TypeError):
object.__setattr__(self, name, value)

def __setitem__(self, key, value):
# support boolean setting with DataFrame input, e.g.
# df[df > df2] = 0
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ def test_getattr(self):
self.assertRaises(AttributeError, getattr, self.frame,
'NONEXISTENT_NAME')

def test_setattr_column(self):
df = DataFrame({'foobar' : 1}, index=range(10))

df.foobar = 5
self.assert_((df.foobar == 5).all())

def test_setitem(self):
# not sure what else to do here
series = self.frame['A'][::2]
Expand Down

0 comments on commit 7e4b086

Please sign in to comment.