Skip to content

ENH: Series item access via attribute #1903 #1904

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
16 changes: 16 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,22 @@ def ix(self):

return self._ix


def __getattr__(self, key):
# make sure there is something to look into
if self.index is not None:
# If attribute is in the Series index ...
if key in self.index:
# ... return item as an attribute
return self[key]
else:
# ... raise the usual exception
raise AttributeError("'Series' object has no attribute '%s'" % key)
else:
# ... raise the usual exception
raise AttributeError("'Series' object has no attribute '%s'" % key)


def __getitem__(self, key):
try:
return self.index.get_value(self, key)
Expand Down
31 changes: 31 additions & 0 deletions pandas/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import operator
import unittest
import types

import nose

Expand Down Expand Up @@ -3133,6 +3134,36 @@ def test_unique_data_ownership(self):
Series(Series(["a","c","b"]).unique()).sort()


def test_dot_notation_items_access(self):
'''
cf #1903
'''
s = Series({'a' : 11, 'b' : 12, 'c' : 13,
'append' : 14, 'T' : 15,
'100' : 16, '*' : 17})

# check dot notation / getattr()
self.assert_(s.a == getattr(s, 'a') == s['a'] == 11)
self.assert_(s.b == getattr(s, 'b') == s['b'] == 12)
self.assert_(s.c == getattr(s, 'c') == s['c'] == 13)

# check getattr() for special keys (no dot notation)
self.assert_(getattr(s, '100') == s['100'] == 16)
self.assert_(getattr(s, '*') == s['*'] == 17)

# check AttributeError on non-existing series keys
self.assertRaises(AttributeError, getattr, s, 'aaa')
self.assertRaises(AttributeError, getattr, s, 'other_key')

# Existing methods/property should overwrite attribute dot notation
self.assert_(isinstance(s.append, types.MethodType))
self.assert_(isinstance(s.T, Series))

# Masked attributes are still available via dict notation
self.assert_(s['append'] == 14)
self.assert_(s['T'] == 15)


if __name__ == '__main__':
nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],
exit=False)