Skip to content

Add simple attribute access to DataFrame columns #213

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,14 @@ def _getitem_single(self, key):
res = Series(values, index=self.index, name=key)
self._series_cache[key] = res
return res

def __getattr__(self, name):
"""After regular attribute access, try looking up the name of a column.
This allows simpler access to columns for interactive use."""
if name in self.columns:
return self[name]
raise AttributeError("'%s' object has no attribute '%s'" % \
(type(self).__name__, name))

def __setitem__(self, key, value):
# support boolean setting with DataFrame input, e.g.
Expand Down
4 changes: 4 additions & 0 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ def test_getitem_boolean(self):

subframe_obj = self.tsframe[indexer_obj]
assert_frame_equal(subframe_obj, subframe)

def test_getattr(self):
tm.assert_series_equal(self.frame.A, self.frame['A'])
self.assertRaises(AttributeError, getattr, self.frame, 'NONEXISTENT_NAME')

def test_setitem(self):
# not sure what else to do here
Expand Down