Skip to content

Commit d883bc2

Browse files
committed
Better TypeError for wrong dtype in str.cat
1 parent 9a42cbe commit d883bc2

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

pandas/core/strings.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2280,6 +2280,14 @@ def cat(self, others=None, sep=None, na_rep=None, join=None):
22802280
'must all be of the same length as the '
22812281
'calling Series/Index.')
22822282

2283+
if any(not (x.dtype == 'O' or (is_categorical_dtype(x)
2284+
and x.cat.categories.dtype == 'O')
2285+
or (x.dtype == 'float' and x.isna().all()))
2286+
for x in others):
2287+
# data has already been checked by str-accessor
2288+
raise TypeError('Can only concatenate list-likes containing only '
2289+
'strings (or missing values)!')
2290+
22832291
if join is None and warn:
22842292
warnings.warn("A future version of pandas will perform index "
22852293
"alignment when `others` is a Series/Index/"

pandas/tests/test_strings.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,15 @@ def test_str_cat_categorical(self, box, dtype_caller, dtype_target, sep):
420420
result = s.str.cat(t, sep=sep)
421421
assert_series_or_index_equal(result, expected)
422422

423+
@pytest.mark.parametrize('box', [Series, Index, np.array, list])
424+
def test_str_cat_raise_wrong_dtype(self, box):
425+
s = Series(['a', 'b', 'c', 'd'])
426+
t = box([1, 2, 3, 4])
427+
428+
msg = 'Can only concatenate list-likes containing only strings.*'
429+
with tm.assert_raises_regex(TypeError, msg):
430+
s.str.cat(t)
431+
423432
@pytest.mark.parametrize('box', [Series, Index])
424433
def test_str_cat_mixed_inputs(self, box):
425434
s = Index(['a', 'b', 'c', 'd'])

0 commit comments

Comments
 (0)