Skip to content

Commit 22a5b56

Browse files
committed
handle all-na Series/Index
1 parent 3eb42e0 commit 22a5b56

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
@@ -367,13 +367,37 @@ def test_str_cat_align_mixed_inputs(self, join):
367367
with tm.assert_raises_regex(ValueError, rgx):
368368
s.str.cat([t, z], join=join)
369369

370-
def test_str_cat_raises(self):
370+
@pytest.mark.parametrize('box', [Series, Index])
371+
def test_str_cat_raises(self, box):
371372
# non-strings hiding behind object dtype
372-
s = Series([1, 2, 3, 4], dtype='object')
373+
s = box([1, 2, 3, 4], dtype='object')
373374
message = 'Can only use .str accessor with string values'
374375
with tm.assert_raises_regex(AttributeError, message):
375376
s.str
376377

378+
@pytest.mark.parametrize('box', [Series, Index])
379+
@pytest.mark.parametrize('other', [Series, Index])
380+
def test_str_cat_all_na(self, box, other):
381+
# check that all NaNs in caller / target work
382+
s = Index(['a', 'b', 'c', 'd'])
383+
s = s if box == Index else Series(s, index=s)
384+
t = other([np.nan] * 4, dtype='object')
385+
# add index of s for alignment
386+
t = t if other == Index else Series(t, index=s)
387+
388+
# all-NA target
389+
expected = Index([np.nan] * 4, dtype='object')
390+
expected = expected if box == Index else Series(expected,
391+
index=s.index)
392+
result = s.str.cat(t, join='left')
393+
assert_series_or_index_equal(result, expected)
394+
395+
# all-NA caller (only for Series)
396+
if other == Series:
397+
expected = Series([np.nan] * 4, dtype='object', index=t.index)
398+
result = t.str.cat(s, join='left')
399+
tm.assert_series_equal(result, expected)
400+
377401
def test_str_cat_special_cases(self):
378402
s = Series(['a', 'b', 'c', 'd'])
379403
t = Series(['d', 'a', 'e', 'b'], index=[3, 0, 4, 1])

0 commit comments

Comments
 (0)