Skip to content

Commit 97fea48

Browse files
bobhaffnerjreback
authored andcommitted
allow neg index on str_get (#17741)
1 parent 72c7a39 commit 97fea48

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

doc/source/whatsnew/v0.21.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,7 @@ Indexing
702702
- Bug in ``IntervalIndex`` where performing a scalar lookup fails for included right endpoints of non-overlapping monotonic decreasing indexes (:issue:`16417`, :issue:`17271`)
703703
- Bug in :meth:`DataFrame.first_valid_index` and :meth:`DataFrame.last_valid_index` when no valid entry (:issue:`17400`)
704704
- Bug in :func:`Series.rename` when called with a `callable`, incorrectly alters the name of the `Series`, rather than the name of the `Index`. (:issue:`17407`)
705+
- Bug in :func:`String.str_get` raises `index out of range` error instead of inserting NaNs when using a negative index. (:issue:`17704`)
705706

706707
I/O
707708
^^^

pandas/core/strings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1260,7 +1260,7 @@ def str_get(arr, i):
12601260
-------
12611261
items : Series/Index of objects
12621262
"""
1263-
f = lambda x: x[i] if len(x) > i else np.nan
1263+
f = lambda x: x[i] if len(x) > i >= -len(x) else np.nan
12641264
return _na_map(f, arr)
12651265

12661266

pandas/tests/test_strings.py

+13
Original file line numberDiff line numberDiff line change
@@ -2484,6 +2484,19 @@ def test_get(self):
24842484
expected = Series([u('b'), u('d'), np.nan, u('g')])
24852485
tm.assert_series_equal(result, expected)
24862486

2487+
# bounds testing
2488+
values = Series(['1_2_3_4_5', '6_7_8_9_10', '11_12'])
2489+
2490+
# positive index
2491+
result = values.str.split('_').str.get(2)
2492+
expected = Series(['3', '8', np.nan])
2493+
tm.assert_series_equal(result, expected)
2494+
2495+
# negative index
2496+
result = values.str.split('_').str.get(-3)
2497+
expected = Series(['3', '8', np.nan])
2498+
tm.assert_series_equal(result, expected)
2499+
24872500
def test_more_contains(self):
24882501
# PR #1179
24892502
s = Series(['A', 'B', 'C', 'Aaba', 'Baca', '', NA,

0 commit comments

Comments
 (0)