Skip to content

Commit f655ff8

Browse files
Dieter Vandenbusschewesm
Dieter Vandenbussche
authored andcommitted
Add get_attr behavior for Panel, similar to DataFrame
Support IPython tab completion for Panel items
1 parent 42a6594 commit f655ff8

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

pandas/core/panel.py

+28
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# pylint: disable=E1103,W0231,W0212,W0621
55

66
import operator
7+
import sys
78
import numpy as np
89

910
from pandas.core.common import (PandasError, _mut_exclusive,
@@ -509,6 +510,14 @@ def set_value(self, item, major, minor, value):
509510
def _box_item_values(self, key, values):
510511
return DataFrame(values, index=self.major_axis, columns=self.minor_axis)
511512

513+
def __getattr__(self, name):
514+
"""After regular attribute access, try looking up the name of an item.
515+
This allows simpler access to items for interactive use."""
516+
if name in self.items:
517+
return self[name]
518+
raise AttributeError("'%s' object has no attribute '%s'" %
519+
(type(self).__name__, name))
520+
512521
def _slice(self, slobj, axis=0):
513522
new_data = self._data.get_slice(slobj, axis=axis)
514523
return self._constructor(new_data)
@@ -1191,3 +1200,22 @@ def _get_distinct_indexes(indexes):
11911200

11921201
def _monotonic(arr):
11931202
return not (arr[1:] < arr[:-1]).any()
1203+
1204+
def install_ipython_completers(): # pragma: no cover
1205+
"""Register the Panel type with IPython's tab completion machinery, so
1206+
that it knows about accessing column names as attributes."""
1207+
from IPython.utils.generics import complete_object
1208+
1209+
@complete_object.when_type(Panel)
1210+
def complete_dataframe(obj, prev_completions):
1211+
return prev_completions + [c for c in obj.items \
1212+
if isinstance(c, basestring) and py3compat.isidentifier(c)]
1213+
1214+
# Importing IPython brings in about 200 modules, so we want to avoid it unless
1215+
# we're in IPython (when those modules are loaded anyway).
1216+
if "IPython" in sys.modules: # pragma: no cover
1217+
try:
1218+
install_ipython_completers()
1219+
except Exception:
1220+
pass
1221+

pandas/tests/test_panel.py

+2
Original file line numberDiff line numberDiff line change
@@ -968,6 +968,8 @@ def test_rename(self):
968968
renamed_nocopy['foo'] = 3.
969969
self.assert_((self.panel['ItemA'].values == 3).all())
970970

971+
def test_get_attr(self):
972+
assert_frame_equal(self.panel['ItemA'], self.panel.ItemA)
971973
def test_group_agg(self):
972974
values = np.ones((10, 2)) * np.arange(10).reshape((10, 1))
973975
bounds = np.arange(5) * 2

0 commit comments

Comments
 (0)