Skip to content

Commit 94f933e

Browse files
committed
handle all-na Series/Index
1 parent 379f2ee commit 94f933e

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

pandas/core/strings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2268,7 +2268,8 @@ def cat(self, others=None, sep=None, na_rep=None, join=None):
22682268
result = cat_core(all_cols, sep)
22692269

22702270
if isinstance(self._orig, Index):
2271-
result = Index(result, name=self._orig.name)
2271+
# add dtype for case that result is all-NA
2272+
result = Index(result, dtype='object', name=self._orig.name)
22722273
else: # Series
22732274
result = Series(result, index=data.index, name=self._orig.name)
22742275
return result

pandas/tests/test_strings.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -377,13 +377,37 @@ def test_str_cat_align_mixed_inputs(self, join):
377377
with tm.assert_raises_regex(ValueError, rgx):
378378
s.str.cat([t, z], join=join)
379379

380-
def test_str_cat_raises(self):
380+
@pytest.mark.parametrize('box', [Series, Index])
381+
def test_str_cat_raises(self, box):
381382
# non-strings hiding behind object dtype
382-
s = Series([1, 2, 3, 4], dtype='object')
383+
s = box([1, 2, 3, 4], dtype='object')
383384
message = 'Can only use .str accessor with string values'
384385
with tm.assert_raises_regex(AttributeError, message):
385386
s.str
386387

388+
@pytest.mark.parametrize('box', [Series, Index])
389+
@pytest.mark.parametrize('other', [Series, Index])
390+
def test_str_cat_all_na(self, box, other):
391+
# check that all NaNs in caller / target work
392+
s = Index(['a', 'b', 'c', 'd'])
393+
s = s if box == Index else Series(s, index=s)
394+
t = other([np.nan] * 4, dtype='object')
395+
# add index of s for alignment
396+
t = t if other == Index else Series(t, index=s)
397+
398+
# all-NA target
399+
expected = Index([np.nan] * 4, dtype='object')
400+
expected = expected if box == Index else Series(expected,
401+
index=s.index)
402+
result = s.str.cat(t, join='left')
403+
assert_series_or_index_equal(result, expected)
404+
405+
# all-NA caller (only for Series)
406+
if other == Series:
407+
expected = Series([np.nan] * 4, dtype='object', index=t.index)
408+
result = t.str.cat(s, join='left')
409+
tm.assert_series_equal(result, expected)
410+
387411
def test_str_cat_special_cases(self):
388412
s = Series(['a', 'b', 'c', 'd'])
389413
t = Series(['d', 'a', 'e', 'b'], index=[3, 0, 4, 1])

0 commit comments

Comments
 (0)