test_cat.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import re
  2. import numpy as np
  3. import pytest
  4. from pandas import (
  5. DataFrame,
  6. Index,
  7. MultiIndex,
  8. Series,
  9. _testing as tm,
  10. concat,
  11. )
  12. def assert_series_or_index_equal(left, right):
  13. if isinstance(left, Series):
  14. tm.assert_series_equal(left, right)
  15. else: # Index
  16. tm.assert_index_equal(left, right)
  17. @pytest.mark.parametrize("other", [None, Series, Index])
  18. def test_str_cat_name(index_or_series, other):
  19. # GH 21053
  20. box = index_or_series
  21. values = ["a", "b"]
  22. if other:
  23. other = other(values)
  24. else:
  25. other = values
  26. result = box(values, name="name").str.cat(other, sep=",")
  27. assert result.name == "name"
  28. def test_str_cat(index_or_series):
  29. box = index_or_series
  30. # test_cat above tests "str_cat" from ndarray;
  31. # here testing "str.cat" from Series/Index to ndarray/list
  32. s = box(["a", "a", "b", "b", "c", np.nan])
  33. # single array
  34. result = s.str.cat()
  35. expected = "aabbc"
  36. assert result == expected
  37. result = s.str.cat(na_rep="-")
  38. expected = "aabbc-"
  39. assert result == expected
  40. result = s.str.cat(sep="_", na_rep="NA")
  41. expected = "a_a_b_b_c_NA"
  42. assert result == expected
  43. t = np.array(["a", np.nan, "b", "d", "foo", np.nan], dtype=object)
  44. expected = box(["aa", "a-", "bb", "bd", "cfoo", "--"])
  45. # Series/Index with array
  46. result = s.str.cat(t, na_rep="-")
  47. assert_series_or_index_equal(result, expected)
  48. # Series/Index with list
  49. result = s.str.cat(list(t), na_rep="-")
  50. assert_series_or_index_equal(result, expected)
  51. # errors for incorrect lengths
  52. rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
  53. z = Series(["1", "2", "3"])
  54. with pytest.raises(ValueError, match=rgx):
  55. s.str.cat(z.values)
  56. with pytest.raises(ValueError, match=rgx):
  57. s.str.cat(list(z))
  58. def test_str_cat_raises_intuitive_error(index_or_series):
  59. # GH 11334
  60. box = index_or_series
  61. s = box(["a", "b", "c", "d"])
  62. message = "Did you mean to supply a `sep` keyword?"
  63. with pytest.raises(ValueError, match=message):
  64. s.str.cat("|")
  65. with pytest.raises(ValueError, match=message):
  66. s.str.cat(" ")
  67. @pytest.mark.parametrize("sep", ["", None])
  68. @pytest.mark.parametrize("dtype_target", ["object", "category"])
  69. @pytest.mark.parametrize("dtype_caller", ["object", "category"])
  70. def test_str_cat_categorical(index_or_series, dtype_caller, dtype_target, sep):
  71. box = index_or_series
  72. s = Index(["a", "a", "b", "a"], dtype=dtype_caller)
  73. s = s if box == Index else Series(s, index=s)
  74. t = Index(["b", "a", "b", "c"], dtype=dtype_target)
  75. expected = Index(["ab", "aa", "bb", "ac"])
  76. expected = expected if box == Index else Series(expected, index=s)
  77. # Series/Index with unaligned Index -> t.values
  78. result = s.str.cat(t.values, sep=sep)
  79. assert_series_or_index_equal(result, expected)
  80. # Series/Index with Series having matching Index
  81. t = Series(t.values, index=s)
  82. result = s.str.cat(t, sep=sep)
  83. assert_series_or_index_equal(result, expected)
  84. # Series/Index with Series.values
  85. result = s.str.cat(t.values, sep=sep)
  86. assert_series_or_index_equal(result, expected)
  87. # Series/Index with Series having different Index
  88. t = Series(t.values, index=t.values)
  89. expected = Index(["aa", "aa", "aa", "bb", "bb"])
  90. expected = expected if box == Index else Series(expected, index=expected.str[:1])
  91. result = s.str.cat(t, sep=sep)
  92. assert_series_or_index_equal(result, expected)
  93. @pytest.mark.parametrize(
  94. "data",
  95. [[1, 2, 3], [0.1, 0.2, 0.3], [1, 2, "b"]],
  96. ids=["integers", "floats", "mixed"],
  97. )
  98. # without dtype=object, np.array would cast [1, 2, 'b'] to ['1', '2', 'b']
  99. @pytest.mark.parametrize(
  100. "box",
  101. [Series, Index, list, lambda x: np.array(x, dtype=object)],
  102. ids=["Series", "Index", "list", "np.array"],
  103. )
  104. def test_str_cat_wrong_dtype_raises(box, data):
  105. # GH 22722
  106. s = Series(["a", "b", "c"])
  107. t = box(data)
  108. msg = "Concatenation requires list-likes containing only strings.*"
  109. with pytest.raises(TypeError, match=msg):
  110. # need to use outer and na_rep, as otherwise Index would not raise
  111. s.str.cat(t, join="outer", na_rep="-")
  112. def test_str_cat_mixed_inputs(index_or_series):
  113. box = index_or_series
  114. s = Index(["a", "b", "c", "d"])
  115. s = s if box == Index else Series(s, index=s)
  116. t = Series(["A", "B", "C", "D"], index=s.values)
  117. d = concat([t, Series(s, index=s)], axis=1)
  118. expected = Index(["aAa", "bBb", "cCc", "dDd"])
  119. expected = expected if box == Index else Series(expected.values, index=s.values)
  120. # Series/Index with DataFrame
  121. result = s.str.cat(d)
  122. assert_series_or_index_equal(result, expected)
  123. # Series/Index with two-dimensional ndarray
  124. result = s.str.cat(d.values)
  125. assert_series_or_index_equal(result, expected)
  126. # Series/Index with list of Series
  127. result = s.str.cat([t, s])
  128. assert_series_or_index_equal(result, expected)
  129. # Series/Index with mixed list of Series/array
  130. result = s.str.cat([t, s.values])
  131. assert_series_or_index_equal(result, expected)
  132. # Series/Index with list of Series; different indexes
  133. t.index = ["b", "c", "d", "a"]
  134. expected = box(["aDa", "bAb", "cBc", "dCd"])
  135. expected = expected if box == Index else Series(expected.values, index=s.values)
  136. result = s.str.cat([t, s])
  137. assert_series_or_index_equal(result, expected)
  138. # Series/Index with mixed list; different index
  139. result = s.str.cat([t, s.values])
  140. assert_series_or_index_equal(result, expected)
  141. # Series/Index with DataFrame; different indexes
  142. d.index = ["b", "c", "d", "a"]
  143. expected = box(["aDd", "bAa", "cBb", "dCc"])
  144. expected = expected if box == Index else Series(expected.values, index=s.values)
  145. result = s.str.cat(d)
  146. assert_series_or_index_equal(result, expected)
  147. # errors for incorrect lengths
  148. rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
  149. z = Series(["1", "2", "3"])
  150. e = concat([z, z], axis=1)
  151. # two-dimensional ndarray
  152. with pytest.raises(ValueError, match=rgx):
  153. s.str.cat(e.values)
  154. # list of list-likes
  155. with pytest.raises(ValueError, match=rgx):
  156. s.str.cat([z.values, s.values])
  157. # mixed list of Series/list-like
  158. with pytest.raises(ValueError, match=rgx):
  159. s.str.cat([z.values, s])
  160. # errors for incorrect arguments in list-like
  161. rgx = "others must be Series, Index, DataFrame,.*"
  162. # make sure None/NaN do not crash checks in _get_series_list
  163. u = Series(["a", np.nan, "c", None])
  164. # mix of string and Series
  165. with pytest.raises(TypeError, match=rgx):
  166. s.str.cat([u, "u"])
  167. # DataFrame in list
  168. with pytest.raises(TypeError, match=rgx):
  169. s.str.cat([u, d])
  170. # 2-dim ndarray in list
  171. with pytest.raises(TypeError, match=rgx):
  172. s.str.cat([u, d.values])
  173. # nested lists
  174. with pytest.raises(TypeError, match=rgx):
  175. s.str.cat([u, [u, d]])
  176. # forbidden input type: set
  177. # GH 23009
  178. with pytest.raises(TypeError, match=rgx):
  179. s.str.cat(set(u))
  180. # forbidden input type: set in list
  181. # GH 23009
  182. with pytest.raises(TypeError, match=rgx):
  183. s.str.cat([u, set(u)])
  184. # other forbidden input type, e.g. int
  185. with pytest.raises(TypeError, match=rgx):
  186. s.str.cat(1)
  187. # nested list-likes
  188. with pytest.raises(TypeError, match=rgx):
  189. s.str.cat(iter([t.values, list(s)]))
  190. @pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
  191. def test_str_cat_align_indexed(index_or_series, join):
  192. # https://github.com/pandas-dev/pandas/issues/18657
  193. box = index_or_series
  194. s = Series(["a", "b", "c", "d"], index=["a", "b", "c", "d"])
  195. t = Series(["D", "A", "E", "B"], index=["d", "a", "e", "b"])
  196. sa, ta = s.align(t, join=join)
  197. # result after manual alignment of inputs
  198. expected = sa.str.cat(ta, na_rep="-")
  199. if box == Index:
  200. s = Index(s)
  201. sa = Index(sa)
  202. expected = Index(expected)
  203. result = s.str.cat(t, join=join, na_rep="-")
  204. assert_series_or_index_equal(result, expected)
  205. @pytest.mark.parametrize("join", ["left", "outer", "inner", "right"])
  206. def test_str_cat_align_mixed_inputs(join):
  207. s = Series(["a", "b", "c", "d"])
  208. t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
  209. d = concat([t, t], axis=1)
  210. expected_outer = Series(["aaa", "bbb", "c--", "ddd", "-ee"])
  211. expected = expected_outer.loc[s.index.join(t.index, how=join)]
  212. # list of Series
  213. result = s.str.cat([t, t], join=join, na_rep="-")
  214. tm.assert_series_equal(result, expected)
  215. # DataFrame
  216. result = s.str.cat(d, join=join, na_rep="-")
  217. tm.assert_series_equal(result, expected)
  218. # mixed list of indexed/unindexed
  219. u = np.array(["A", "B", "C", "D"])
  220. expected_outer = Series(["aaA", "bbB", "c-C", "ddD", "-e-"])
  221. # joint index of rhs [t, u]; u will be forced have index of s
  222. rhs_idx = (
  223. t.index.intersection(s.index)
  224. if join == "inner"
  225. else t.index.union(s.index)
  226. if join == "outer"
  227. else t.index.append(s.index.difference(t.index))
  228. )
  229. expected = expected_outer.loc[s.index.join(rhs_idx, how=join)]
  230. result = s.str.cat([t, u], join=join, na_rep="-")
  231. tm.assert_series_equal(result, expected)
  232. with pytest.raises(TypeError, match="others must be Series,.*"):
  233. # nested lists are forbidden
  234. s.str.cat([t, list(u)], join=join)
  235. # errors for incorrect lengths
  236. rgx = r"If `others` contains arrays or lists \(or other list-likes.*"
  237. z = Series(["1", "2", "3"]).values
  238. # unindexed object of wrong length
  239. with pytest.raises(ValueError, match=rgx):
  240. s.str.cat(z, join=join)
  241. # unindexed object of wrong length in list
  242. with pytest.raises(ValueError, match=rgx):
  243. s.str.cat([t, z], join=join)
  244. def test_str_cat_all_na(index_or_series, index_or_series2):
  245. # GH 24044
  246. box = index_or_series
  247. other = index_or_series2
  248. # check that all NaNs in caller / target work
  249. s = Index(["a", "b", "c", "d"])
  250. s = s if box == Index else Series(s, index=s)
  251. t = other([np.nan] * 4, dtype=object)
  252. # add index of s for alignment
  253. t = t if other == Index else Series(t, index=s)
  254. # all-NA target
  255. if box == Series:
  256. expected = Series([np.nan] * 4, index=s.index, dtype=object)
  257. else: # box == Index
  258. expected = Index([np.nan] * 4, dtype=object)
  259. result = s.str.cat(t, join="left")
  260. assert_series_or_index_equal(result, expected)
  261. # all-NA caller (only for Series)
  262. if other == Series:
  263. expected = Series([np.nan] * 4, dtype=object, index=t.index)
  264. result = t.str.cat(s, join="left")
  265. tm.assert_series_equal(result, expected)
  266. def test_str_cat_special_cases():
  267. s = Series(["a", "b", "c", "d"])
  268. t = Series(["d", "a", "e", "b"], index=[3, 0, 4, 1])
  269. # iterator of elements with different types
  270. expected = Series(["aaa", "bbb", "c-c", "ddd", "-e-"])
  271. result = s.str.cat(iter([t, s.values]), join="outer", na_rep="-")
  272. tm.assert_series_equal(result, expected)
  273. # right-align with different indexes in others
  274. expected = Series(["aa-", "d-d"], index=[0, 3])
  275. result = s.str.cat([t.loc[[0]], t.loc[[3]]], join="right", na_rep="-")
  276. tm.assert_series_equal(result, expected)
  277. def test_cat_on_filtered_index():
  278. df = DataFrame(
  279. index=MultiIndex.from_product(
  280. [[2011, 2012], [1, 2, 3]], names=["year", "month"]
  281. )
  282. )
  283. df = df.reset_index()
  284. df = df[df.month > 1]
  285. str_year = df.year.astype("str")
  286. str_month = df.month.astype("str")
  287. str_both = str_year.str.cat(str_month, sep=" ")
  288. assert str_both.loc[1] == "2011 2"
  289. str_multiple = str_year.str.cat([str_month, str_month], sep=" ")
  290. assert str_multiple.loc[1] == "2011 2 2"
  291. @pytest.mark.parametrize("klass", [tuple, list, np.array, Series, Index])
  292. def test_cat_different_classes(klass):
  293. # https://github.com/pandas-dev/pandas/issues/33425
  294. s = Series(["a", "b", "c"])
  295. result = s.str.cat(klass(["x", "y", "z"]))
  296. expected = Series(["ax", "by", "cz"])
  297. tm.assert_series_equal(result, expected)
  298. def test_cat_on_series_dot_str():
  299. # GH 28277
  300. ps = Series(["AbC", "de", "FGHI", "j", "kLLLm"])
  301. message = re.escape(
  302. "others must be Series, Index, DataFrame, np.ndarray "
  303. "or list-like (either containing only strings or "
  304. "containing only objects of type Series/Index/"
  305. "np.ndarray[1-dim])"
  306. )
  307. with pytest.raises(TypeError, match=message):
  308. ps.str.cat(others=ps.str)