Skip to content

Commit

Permalink
ENH: better string element access/slicing notation close pandas-dev#1656
Browse files Browse the repository at this point in the history
  • Loading branch information
wesm committed Jul 22, 2012
1 parent 930652f commit 3839f64
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
13 changes: 10 additions & 3 deletions pandas/core/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,7 @@ def str_split(arr, pat, n=0):
return _na_map(f, arr)


def str_slice(arr, start=None, stop=None):
def str_slice(arr, start=None, stop=None, step=1):
"""
Slice substrings from each element in array
Expand All @@ -519,7 +519,7 @@ def str_slice(arr, start=None, stop=None):
-------
sliced : array
"""
obj = slice(start, stop)
obj = slice(start, stop, step)
f = lambda x: x[obj]
return _na_map(f, arr)

Expand Down Expand Up @@ -649,6 +649,13 @@ class StringMethods(object):
def __init__(self, series):
self.series = series

def __getitem__(self, key):
if isinstance(key, slice):
return self.slice(start=key.start, stop=key.stop,
step=key.step)
else:
return self.get(key)

def _wrap_result(self, result):
return Series(result, index=self.series.index,
name=self.series.name)
Expand Down Expand Up @@ -699,7 +706,7 @@ def center(self, width):
return self._wrap_result(result)

@copy(str_slice)
def slice(self, start=None, stop=None):
def slice(self, start=None, stop=None, step=1):
result = str_slice(self.series, start, stop)
return self._wrap_result(result)

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,18 @@ def test_more_replace(self):
'XX-XX BA', 'XX-XX ', 'XX-XX t'])
assert_series_equal(result, expected)

def test_string_slice_get_syntax(self):
s = Series(['YYY', 'B', 'C', 'YYYYYYbYYY', 'BYYYcYYY', NA,
'CYYYBYYY', 'dog', 'cYYYt'])

result = s.str[0]
expected = s.str.get(0)
assert_series_equal(result, expected)

result = s.str[:3]
expected = s.str.slice(stop=3)
assert_series_equal(result, expected)

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

0 comments on commit 3839f64

Please sign in to comment.