Skip to content

Improvements to str_cat #12297

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 2 commits 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
32 changes: 32 additions & 0 deletions doc/source/whatsnew/v0.18.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,38 @@ the ``extractall`` method returns all matches.

.. _whatsnew_0180.enhancements.rounding:


Changes to str.cat
^^^^^^^^^^^^^^^^^^

The :ref:`.str.cat <text.cat>` concatenates the members of a Series. Before, if NaN values
were present in the Series, calling `cat()` on it would return NaN, unlike the rest of the
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use double backticks around NaN & Series, don't use 'cat()', use .str.cat()

`Series.str.*` API. This behavior has been amended to ignore NaN values by default.
(:issue:`11435`).

A new, friendlier ValueError was also added to protect against the mistake of supplying the
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

double backticks around ValueError

`sep` as an arg, rather than a kwarg.
(:issue:`11334`).

.. code-block:: python
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make the first 2 an ipython block so they run, the 3rd can be a code-block (just so you can show the error and not the entire traceback)


>>> Series(['a','b',np.nan,'c']).str.cat(sep=' ')
'a b c'

>>> Series(['a','b',np.nan,'c']).str.cat(sep=' ', na_rep='?')
'a b ? c'

>>> Series(['a','b',np.nan,'c']).str.cat(' ')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-338c379049e9> in <module>()
----> 1 Series(['a','b',np.nan,'c']).str.cat(' ')

[...]

ValueError: Did you mean to supply a `sep` keyword?


Datetimelike rounding
^^^^^^^^^^^^^^^^^^^^^

Expand Down
30 changes: 22 additions & 8 deletions pandas/core/strings.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import numpy as np

from pandas.compat import zip
from pandas.core.common import (isnull, _values_from_object, is_bool_dtype,
from pandas.core.common import (isnull, notnull, _values_from_object, is_bool_dtype,
is_list_like, is_categorical_dtype,
is_object_dtype, take_1d)
import pandas.compat as compat
Expand Down Expand Up @@ -37,14 +37,23 @@ def str_cat(arr, others=None, sep=None, na_rep=None):
If None, returns str concatenating strings of the Series
sep : string or None, default None
na_rep : string or None, default None
If None, an NA in any array will propagate
If None, NA in the series are ignored.

Returns
-------
concat : Series/Index of objects or str

Examples
--------
When ``na_rep`` is `None` (default behavior), NaN value(s)
in the Series are ignored.

>>> Series(['a','b',np.nan,'c']).str.cat(sep=' ')
'a b c'

>>> Series(['a','b',np.nan,'c']).str.cat(sep=' ', na_rep='?')
'a b ? c'

If ``others`` is specified, corresponding values are
concatenated with the separator. Result will be a Series of strings.

Expand Down Expand Up @@ -103,18 +112,23 @@ def str_cat(arr, others=None, sep=None, na_rep=None):
arr = np.asarray(arr, dtype=object)
mask = isnull(arr)
if na_rep is None and mask.any():
return np.nan
if sep == '':
na_rep = ''
else:
return sep.join(arr[notnull(arr)])
return sep.join(np.where(mask, na_rep, arr))


def _length_check(others):
n = None
for x in others:
if n is None:
n = len(x)
elif len(x) != n:
raise ValueError('All arrays must be same length')

try:
if n is None:
n = len(x)
elif len(x) != n:
raise ValueError('All arrays must be same length')
except TypeError:
raise ValueError("Did you mean to supply a `sep` keyword?")
return n


Expand Down
17 changes: 16 additions & 1 deletion pandas/tests/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ def test_cat(self):

# single array
result = strings.str_cat(one)
self.assertTrue(isnull(result))
exp = 'aabbc'
self.assertEqual(result, exp)

result = strings.str_cat(one, na_rep='NA')
exp = 'aabbcNA'
Expand All @@ -114,6 +115,10 @@ def test_cat(self):
exp = 'a_a_b_b_c_NA'
self.assertEqual(result, exp)

result = strings.str_cat(two, sep='-')
exp = 'a-b-d-foo'
self.assertEqual(result, exp)

# Multiple arrays
result = strings.str_cat(one, [two], na_rep='NA')
exp = ['aa', 'aNA', 'bb', 'bd', 'cfoo', 'NANA']
Expand Down Expand Up @@ -2453,6 +2458,16 @@ def test_cat_on_filtered_index(self):

self.assertEqual(str_multiple.loc[1], '2011 2 2')

def test_str_cat_raises_intuitive_error(self):
# https://github.com/pydata/pandas/issues/11334
s = Series(['a','b','c','d'])
message = "Did you mean to supply a `sep` keyword?"
with tm.assertRaisesRegexp(ValueError, message):
s.str.cat('|')
with tm.assertRaisesRegexp(ValueError, message):
s.str.cat(' ')


def test_index_str_accessor_visibility(self):
from pandas.core.strings import StringMethods

Expand Down