Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Add simple attribute access to DataFrame columns #213

Closed
wants to merge 1 commit into from

2 participants

@takluyver
Collaborator

This one might need some discussion, but I think it makes sense.

If a column name in a dataframe is a valid Python name and doesn't conflict with any DataFrame attributes, this lets you type df.MyColumn than df['MyColumn']. That's much handier for interactive use, especially because IPython will tab complete df.MyColumn.<tab>, while it won't by default tab complete df['MyColumn'].<tab>.

This doesn't interfere with accessing columns through the dictionary interface.

@wesm
Owner

This seems useful-- it might even be possible to get tab completion but the overall computational cost (overriding __getattribute__) might be too great. Merged it into master. Thanks!

@wesm wesm closed this
@takluyver
Collaborator

Thanks. I think there's a method by which objects can expose extra things for tab completion to IPython, but I that's a lower priority.

Just looking at the code, I think we'd need to register the DataFrame type with IPython.utils.generic.complete_object (see code here). I'll get round to doing it at some point.

@wesm
Owner

I created an issue about this:

https://github.com/wesm/pandas/issues/230

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Oct 10, 2011
  1. @takluyver
This page is out of date. Refresh to see the latest.
Showing with 12 additions and 0 deletions.
  1. +8 −0 pandas/core/frame.py
  2. +4 −0 pandas/tests/test_frame.py
View
8 pandas/core/frame.py
@@ -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.
View
4 pandas/tests/test_frame.py
@@ -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
Something went wrong with that request. Please try again.