Skip to content

Commit 45f69cd

Browse files
Merge pull request #9773 from sinhrks/partition
ENH: Add StringMethods.partition and rpartition
2 parents b229057 + 00c2408 commit 45f69cd

File tree

5 files changed

+214
-0
lines changed

5 files changed

+214
-0
lines changed

doc/source/api.rst

+2
Original file line numberDiff line numberDiff line change
@@ -544,10 +544,12 @@ strings and apply several methods to it. These can be acccessed like
544544
Series.str.match
545545
Series.str.normalize
546546
Series.str.pad
547+
Series.str.partition
547548
Series.str.repeat
548549
Series.str.replace
549550
Series.str.rfind
550551
Series.str.rjust
552+
Series.str.rpartition
551553
Series.str.rstrip
552554
Series.str.slice
553555
Series.str.slice_replace

doc/source/text.rst

+2
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,8 @@ Method Summary
262262
:meth:`~Series.str.strip`,Equivalent to ``str.strip``
263263
:meth:`~Series.str.rstrip`,Equivalent to ``str.rstrip``
264264
:meth:`~Series.str.lstrip`,Equivalent to ``str.lstrip``
265+
:meth:`~Series.str.partition`,Equivalent to ``str.partition``
266+
:meth:`~Series.str.rpartition`,Equivalent to ``str.rpartition``
265267
:meth:`~Series.str.lower`,Equivalent to ``str.lower``
266268
:meth:`~Series.str.upper`,Equivalent to ``str.upper``
267269
:meth:`~Series.str.find`,Equivalent to ``str.find``

doc/source/whatsnew/v0.16.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Enhancements
4242
- Added ``StringMethods`` (.str accessor) to ``Index`` (:issue:`9068`)
4343
- Added ``StringMethods.normalize()`` which behaves the same as standard :func:`unicodedata.normalizes` (:issue:`10031`)
4444

45+
- Added ``StringMethods.partition()`` and ``rpartition()`` which behave as the same as standard ``str`` (:issue:`9773`)
4546
- Allow clip, clip_lower, and clip_upper to accept array-like arguments as thresholds (:issue:`6966`). These methods now have an ``axis`` parameter which determines how the Series or DataFrame will be aligned with the threshold(s).
4647

4748
The ``.str`` accessor is now available for both ``Series`` and ``Index``.

pandas/core/strings.py

+88
Original file line numberDiff line numberDiff line change
@@ -992,6 +992,8 @@ def __iter__(self):
992992
g = self.get(i)
993993

994994
def _wrap_result(self, result):
995+
# leave as it is to keep extract and get_dummies results
996+
# can be merged to _wrap_result_expand in v0.17
995997
from pandas.core.series import Series
996998
from pandas.core.frame import DataFrame
997999
from pandas.core.index import Index
@@ -1012,6 +1014,33 @@ def _wrap_result(self, result):
10121014
assert result.ndim < 3
10131015
return DataFrame(result, index=self.series.index)
10141016

1017+
def _wrap_result_expand(self, result, expand=False):
1018+
from pandas.core.index import Index
1019+
if not hasattr(result, 'ndim'):
1020+
return result
1021+
1022+
if isinstance(self.series, Index):
1023+
name = getattr(result, 'name', None)
1024+
# if result is a boolean np.array, return the np.array
1025+
# instead of wrapping it into a boolean Index (GH 8875)
1026+
if hasattr(result, 'dtype') and is_bool_dtype(result):
1027+
return result
1028+
1029+
if expand:
1030+
result = list(result)
1031+
return Index(result, name=name)
1032+
else:
1033+
index = self.series.index
1034+
if expand:
1035+
cons_row = self.series._constructor
1036+
cons = self.series._constructor_expanddim
1037+
data = [cons_row(x) for x in result]
1038+
return cons(data, index=index)
1039+
else:
1040+
name = getattr(result, 'name', None)
1041+
cons = self.series._constructor
1042+
return cons(result, name=name, index=index)
1043+
10151044
@copy(str_cat)
10161045
def cat(self, others=None, sep=None, na_rep=None):
10171046
result = str_cat(self.series, others=others, sep=sep, na_rep=na_rep)
@@ -1022,6 +1051,65 @@ def split(self, pat=None, n=-1, return_type='series'):
10221051
result = str_split(self.series, pat, n=n, return_type=return_type)
10231052
return self._wrap_result(result)
10241053

1054+
_shared_docs['str_partition'] = ("""
1055+
Split the string at the %(side)s occurrence of `sep`, and return 3 elements
1056+
containing the part before the separator, the separator itself,
1057+
and the part after the separator.
1058+
If the separator is not found, return %(return)s.
1059+
1060+
Parameters
1061+
----------
1062+
pat : string, default whitespace
1063+
String to split on.
1064+
expand : bool, default True
1065+
* If True, return DataFrame/MultiIndex expanding dimensionality.
1066+
* If False, return Series/Index
1067+
1068+
Returns
1069+
-------
1070+
split : DataFrame/MultiIndex or Series/Index of objects
1071+
1072+
See Also
1073+
--------
1074+
%(also)s
1075+
1076+
Examples
1077+
--------
1078+
1079+
>>> s = Series(['A_B_C', 'D_E_F', 'X'])
1080+
0 A_B_C
1081+
1 D_E_F
1082+
2 X
1083+
dtype: object
1084+
1085+
>>> s.str.partition('_')
1086+
0 1 2
1087+
0 A _ B_C
1088+
1 D _ E_F
1089+
2 X
1090+
1091+
>>> s.str.rpartition('_')
1092+
0 1 2
1093+
0 A_B _ C
1094+
1 D_E _ F
1095+
2 X
1096+
""")
1097+
@Appender(_shared_docs['str_partition'] % {'side': 'first',
1098+
'return': '3 elements containing the string itself, followed by two empty strings',
1099+
'also': 'rpartition : Split the string at the last occurrence of `sep`'})
1100+
def partition(self, pat=' ', expand=True):
1101+
f = lambda x: x.partition(pat)
1102+
result = _na_map(f, self.series)
1103+
return self._wrap_result_expand(result, expand=expand)
1104+
1105+
@Appender(_shared_docs['str_partition'] % {'side': 'last',
1106+
'return': '3 elements containing two empty strings, followed by the string itself',
1107+
'also': 'partition : Split the string at the first occurrence of `sep`'})
1108+
def rpartition(self, pat=' ', expand=True):
1109+
f = lambda x: x.rpartition(pat)
1110+
result = _na_map(f, self.series)
1111+
return self._wrap_result_expand(result, expand=expand)
1112+
10251113
@copy(str_get)
10261114
def get(self, i):
10271115
result = str_get(self.series, i)

pandas/tests/test_strings.py

+121
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,8 @@ def test_empty_str_methods(self):
664664
tm.assert_series_equal(empty_str, empty.str.pad(42))
665665
tm.assert_series_equal(empty_str, empty.str.center(42))
666666
tm.assert_series_equal(empty_list, empty.str.split('a'))
667+
tm.assert_series_equal(empty_list, empty.str.partition('a', expand=False))
668+
tm.assert_series_equal(empty_list, empty.str.rpartition('a', expand=False))
667669
tm.assert_series_equal(empty_str, empty.str.slice(stop=1))
668670
tm.assert_series_equal(empty_str, empty.str.slice(step=1))
669671
tm.assert_series_equal(empty_str, empty.str.strip())
@@ -687,6 +689,12 @@ def test_empty_str_methods(self):
687689
tm.assert_series_equal(empty_str, empty.str.swapcase())
688690
tm.assert_series_equal(empty_str, empty.str.normalize('NFC'))
689691

692+
def test_empty_str_methods_to_frame(self):
693+
empty_str = empty = Series(dtype=str)
694+
empty_df = DataFrame([])
695+
tm.assert_frame_equal(empty_df, empty.str.partition('a'))
696+
tm.assert_frame_equal(empty_df, empty.str.rpartition('a'))
697+
690698
def test_ismethods(self):
691699
values = ['A', 'b', 'Xy', '4', '3A', '', 'TT', '55', '-', ' ']
692700
str_s = Series(values)
@@ -1175,6 +1183,119 @@ def test_split_to_dataframe(self):
11751183
with tm.assertRaisesRegexp(ValueError, "return_type must be"):
11761184
s.str.split('_', return_type="some_invalid_type")
11771185

1186+
def test_partition_series(self):
1187+
values = Series(['a_b_c', 'c_d_e', NA, 'f_g_h'])
1188+
1189+
result = values.str.partition('_', expand=False)
1190+
exp = Series([['a', '_', 'b_c'], ['c', '_', 'd_e'], NA, ['f', '_', 'g_h']])
1191+
tm.assert_series_equal(result, exp)
1192+
1193+
result = values.str.rpartition('_', expand=False)
1194+
exp = Series([['a_b', '_', 'c'], ['c_d', '_', 'e'], NA, ['f_g', '_', 'h']])
1195+
tm.assert_series_equal(result, exp)
1196+
1197+
# more than one char
1198+
values = Series(['a__b__c', 'c__d__e', NA, 'f__g__h'])
1199+
result = values.str.partition('__', expand=False)
1200+
exp = Series([['a', '__', 'b__c'], ['c', '__', 'd__e'], NA, ['f', '__', 'g__h']])
1201+
tm.assert_series_equal(result, exp)
1202+
1203+
result = values.str.rpartition('__', expand=False)
1204+
exp = Series([['a__b', '__', 'c'], ['c__d', '__', 'e'], NA, ['f__g', '__', 'h']])
1205+
tm.assert_series_equal(result, exp)
1206+
1207+
# None
1208+
values = Series(['a b c', 'c d e', NA, 'f g h'])
1209+
result = values.str.partition(expand=False)
1210+
exp = Series([['a', ' ', 'b c'], ['c', ' ', 'd e'], NA, ['f', ' ', 'g h']])
1211+
tm.assert_series_equal(result, exp)
1212+
1213+
result = values.str.rpartition(expand=False)
1214+
exp = Series([['a b', ' ', 'c'], ['c d', ' ', 'e'], NA, ['f g', ' ', 'h']])
1215+
tm.assert_series_equal(result, exp)
1216+
1217+
# Not splited
1218+
values = Series(['abc', 'cde', NA, 'fgh'])
1219+
result = values.str.partition('_', expand=False)
1220+
exp = Series([['abc', '', ''], ['cde', '', ''], NA, ['fgh', '', '']])
1221+
tm.assert_series_equal(result, exp)
1222+
1223+
result = values.str.rpartition('_', expand=False)
1224+
exp = Series([['', '', 'abc'], ['', '', 'cde'], NA, ['', '', 'fgh']])
1225+
tm.assert_series_equal(result, exp)
1226+
1227+
# unicode
1228+
values = Series([u('a_b_c'), u('c_d_e'), NA, u('f_g_h')])
1229+
1230+
result = values.str.partition('_', expand=False)
1231+
exp = Series([[u('a'), u('_'), u('b_c')], [u('c'), u('_'), u('d_e')],
1232+
NA, [u('f'), u('_'), u('g_h')]])
1233+
tm.assert_series_equal(result, exp)
1234+
1235+
result = values.str.rpartition('_', expand=False)
1236+
exp = Series([[u('a_b'), u('_'), u('c')], [u('c_d'), u('_'), u('e')],
1237+
NA, [u('f_g'), u('_'), u('h')]])
1238+
tm.assert_series_equal(result, exp)
1239+
1240+
# compare to standard lib
1241+
values = Series(['A_B_C', 'B_C_D', 'E_F_G', 'EFGHEF'])
1242+
result = values.str.partition('_', expand=False).tolist()
1243+
self.assertEqual(result, [v.partition('_') for v in values])
1244+
result = values.str.rpartition('_', expand=False).tolist()
1245+
self.assertEqual(result, [v.rpartition('_') for v in values])
1246+
1247+
def test_partition_index(self):
1248+
values = Index(['a_b_c', 'c_d_e', 'f_g_h'])
1249+
1250+
result = values.str.partition('_', expand=False)
1251+
exp = Index(np.array([('a', '_', 'b_c'), ('c', '_', 'd_e'), ('f', '_', 'g_h')]))
1252+
tm.assert_index_equal(result, exp)
1253+
self.assertEqual(result.nlevels, 1)
1254+
1255+
result = values.str.rpartition('_', expand=False)
1256+
exp = Index(np.array([('a_b', '_', 'c'), ('c_d', '_', 'e'), ('f_g', '_', 'h')]))
1257+
tm.assert_index_equal(result, exp)
1258+
self.assertEqual(result.nlevels, 1)
1259+
1260+
result = values.str.partition('_')
1261+
exp = Index([('a', '_', 'b_c'), ('c', '_', 'd_e'), ('f', '_', 'g_h')])
1262+
tm.assert_index_equal(result, exp)
1263+
self.assertTrue(isinstance(result, MultiIndex))
1264+
self.assertEqual(result.nlevels, 3)
1265+
1266+
result = values.str.rpartition('_')
1267+
exp = Index([('a_b', '_', 'c'), ('c_d', '_', 'e'), ('f_g', '_', 'h')])
1268+
tm.assert_index_equal(result, exp)
1269+
self.assertTrue(isinstance(result, MultiIndex))
1270+
self.assertEqual(result.nlevels, 3)
1271+
1272+
def test_partition_to_dataframe(self):
1273+
values = Series(['a_b_c', 'c_d_e', NA, 'f_g_h'])
1274+
result = values.str.partition('_')
1275+
exp = DataFrame({0: ['a', 'c', np.nan, 'f'],
1276+
1: ['_', '_', np.nan, '_'],
1277+
2: ['b_c', 'd_e', np.nan, 'g_h']})
1278+
tm.assert_frame_equal(result, exp)
1279+
1280+
result = values.str.rpartition('_')
1281+
exp = DataFrame({0: ['a_b', 'c_d', np.nan, 'f_g'],
1282+
1: ['_', '_', np.nan, '_'],
1283+
2: ['c', 'e', np.nan, 'h']})
1284+
tm.assert_frame_equal(result, exp)
1285+
1286+
values = Series(['a_b_c', 'c_d_e', NA, 'f_g_h'])
1287+
result = values.str.partition('_', expand=True)
1288+
exp = DataFrame({0: ['a', 'c', np.nan, 'f'],
1289+
1: ['_', '_', np.nan, '_'],
1290+
2: ['b_c', 'd_e', np.nan, 'g_h']})
1291+
tm.assert_frame_equal(result, exp)
1292+
1293+
result = values.str.rpartition('_', expand=True)
1294+
exp = DataFrame({0: ['a_b', 'c_d', np.nan, 'f_g'],
1295+
1: ['_', '_', np.nan, '_'],
1296+
2: ['c', 'e', np.nan, 'h']})
1297+
tm.assert_frame_equal(result, exp)
1298+
11781299
def test_pipe_failures(self):
11791300
# #2119
11801301
s = Series(['A|B|C'])

0 commit comments

Comments
 (0)