test_align.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. from datetime import timezone
  2. import numpy as np
  3. import pytest
  4. import pandas as pd
  5. from pandas import (
  6. DataFrame,
  7. Index,
  8. Series,
  9. date_range,
  10. )
  11. import pandas._testing as tm
  12. class TestDataFrameAlign:
  13. def test_frame_align_aware(self):
  14. idx1 = date_range("2001", periods=5, freq="H", tz="US/Eastern")
  15. idx2 = date_range("2001", periods=5, freq="2H", tz="US/Eastern")
  16. df1 = DataFrame(np.random.randn(len(idx1), 3), idx1)
  17. df2 = DataFrame(np.random.randn(len(idx2), 3), idx2)
  18. new1, new2 = df1.align(df2)
  19. assert df1.index.tz == new1.index.tz
  20. assert df2.index.tz == new2.index.tz
  21. # different timezones convert to UTC
  22. # frame with frame
  23. df1_central = df1.tz_convert("US/Central")
  24. new1, new2 = df1.align(df1_central)
  25. assert new1.index.tz is timezone.utc
  26. assert new2.index.tz is timezone.utc
  27. # frame with Series
  28. new1, new2 = df1.align(df1_central[0], axis=0)
  29. assert new1.index.tz is timezone.utc
  30. assert new2.index.tz is timezone.utc
  31. df1[0].align(df1_central, axis=0)
  32. assert new1.index.tz is timezone.utc
  33. assert new2.index.tz is timezone.utc
  34. def test_align_float(self, float_frame, using_copy_on_write):
  35. af, bf = float_frame.align(float_frame)
  36. assert af._mgr is not float_frame._mgr
  37. af, bf = float_frame.align(float_frame, copy=False)
  38. if not using_copy_on_write:
  39. assert af._mgr is float_frame._mgr
  40. else:
  41. assert af._mgr is not float_frame._mgr
  42. # axis = 0
  43. other = float_frame.iloc[:-5, :3]
  44. af, bf = float_frame.align(other, axis=0, fill_value=-1)
  45. tm.assert_index_equal(bf.columns, other.columns)
  46. # test fill value
  47. join_idx = float_frame.index.join(other.index)
  48. diff_a = float_frame.index.difference(join_idx)
  49. diff_a_vals = af.reindex(diff_a).values
  50. assert (diff_a_vals == -1).all()
  51. af, bf = float_frame.align(other, join="right", axis=0)
  52. tm.assert_index_equal(bf.columns, other.columns)
  53. tm.assert_index_equal(bf.index, other.index)
  54. tm.assert_index_equal(af.index, other.index)
  55. # axis = 1
  56. other = float_frame.iloc[:-5, :3].copy()
  57. af, bf = float_frame.align(other, axis=1)
  58. tm.assert_index_equal(bf.columns, float_frame.columns)
  59. tm.assert_index_equal(bf.index, other.index)
  60. # test fill value
  61. join_idx = float_frame.index.join(other.index)
  62. diff_a = float_frame.index.difference(join_idx)
  63. diff_a_vals = af.reindex(diff_a).values
  64. assert (diff_a_vals == -1).all()
  65. af, bf = float_frame.align(other, join="inner", axis=1)
  66. tm.assert_index_equal(bf.columns, other.columns)
  67. af, bf = float_frame.align(other, join="inner", axis=1, method="pad")
  68. tm.assert_index_equal(bf.columns, other.columns)
  69. af, bf = float_frame.align(
  70. other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=None
  71. )
  72. tm.assert_index_equal(bf.index, Index([]))
  73. af, bf = float_frame.align(
  74. other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
  75. )
  76. tm.assert_index_equal(bf.index, Index([]))
  77. # Try to align DataFrame to Series along bad axis
  78. msg = "No axis named 2 for object type DataFrame"
  79. with pytest.raises(ValueError, match=msg):
  80. float_frame.align(af.iloc[0, :3], join="inner", axis=2)
  81. # align dataframe to series with broadcast or not
  82. idx = float_frame.index
  83. s = Series(range(len(idx)), index=idx)
  84. left, right = float_frame.align(s, axis=0)
  85. tm.assert_index_equal(left.index, float_frame.index)
  86. tm.assert_index_equal(right.index, float_frame.index)
  87. assert isinstance(right, Series)
  88. left, right = float_frame.align(s, broadcast_axis=1)
  89. tm.assert_index_equal(left.index, float_frame.index)
  90. expected = {c: s for c in float_frame.columns}
  91. expected = DataFrame(
  92. expected, index=float_frame.index, columns=float_frame.columns
  93. )
  94. tm.assert_frame_equal(right, expected)
  95. # see gh-9558
  96. df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
  97. result = df[df["a"] == 2]
  98. expected = DataFrame([[2, 5]], index=[1], columns=["a", "b"])
  99. tm.assert_frame_equal(result, expected)
  100. result = df.where(df["a"] == 2, 0)
  101. expected = DataFrame({"a": [0, 2, 0], "b": [0, 5, 0]})
  102. tm.assert_frame_equal(result, expected)
  103. def test_align_int(self, int_frame):
  104. # test other non-float types
  105. other = DataFrame(index=range(5), columns=["A", "B", "C"])
  106. af, bf = int_frame.align(other, join="inner", axis=1, method="pad")
  107. tm.assert_index_equal(bf.columns, other.columns)
  108. def test_align_mixed_type(self, float_string_frame):
  109. af, bf = float_string_frame.align(
  110. float_string_frame, join="inner", axis=1, method="pad"
  111. )
  112. tm.assert_index_equal(bf.columns, float_string_frame.columns)
  113. def test_align_mixed_float(self, mixed_float_frame):
  114. # mixed floats/ints
  115. other = DataFrame(index=range(5), columns=["A", "B", "C"])
  116. af, bf = mixed_float_frame.align(
  117. other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
  118. )
  119. tm.assert_index_equal(bf.index, Index([]))
  120. def test_align_mixed_int(self, mixed_int_frame):
  121. other = DataFrame(index=range(5), columns=["A", "B", "C"])
  122. af, bf = mixed_int_frame.align(
  123. other.iloc[:, 0], join="inner", axis=1, method=None, fill_value=0
  124. )
  125. tm.assert_index_equal(bf.index, Index([]))
  126. @pytest.mark.parametrize(
  127. "l_ordered,r_ordered,expected",
  128. [
  129. [True, True, pd.CategoricalIndex],
  130. [True, False, Index],
  131. [False, True, Index],
  132. [False, False, pd.CategoricalIndex],
  133. ],
  134. )
  135. def test_align_categorical(self, l_ordered, r_ordered, expected):
  136. # GH-28397
  137. df_1 = DataFrame(
  138. {
  139. "A": np.arange(6, dtype="int64"),
  140. "B": Series(list("aabbca")).astype(
  141. pd.CategoricalDtype(list("cab"), ordered=l_ordered)
  142. ),
  143. }
  144. ).set_index("B")
  145. df_2 = DataFrame(
  146. {
  147. "A": np.arange(5, dtype="int64"),
  148. "B": Series(list("babca")).astype(
  149. pd.CategoricalDtype(list("cab"), ordered=r_ordered)
  150. ),
  151. }
  152. ).set_index("B")
  153. aligned_1, aligned_2 = df_1.align(df_2)
  154. assert isinstance(aligned_1.index, expected)
  155. assert isinstance(aligned_2.index, expected)
  156. tm.assert_index_equal(aligned_1.index, aligned_2.index)
  157. def test_align_multiindex(self):
  158. # GH#10665
  159. # same test cases as test_align_multiindex in test_series.py
  160. midx = pd.MultiIndex.from_product(
  161. [range(2), range(3), range(2)], names=("a", "b", "c")
  162. )
  163. idx = Index(range(2), name="b")
  164. df1 = DataFrame(np.arange(12, dtype="int64"), index=midx)
  165. df2 = DataFrame(np.arange(2, dtype="int64"), index=idx)
  166. # these must be the same results (but flipped)
  167. res1l, res1r = df1.align(df2, join="left")
  168. res2l, res2r = df2.align(df1, join="right")
  169. expl = df1
  170. tm.assert_frame_equal(expl, res1l)
  171. tm.assert_frame_equal(expl, res2r)
  172. expr = DataFrame([0, 0, 1, 1, np.nan, np.nan] * 2, index=midx)
  173. tm.assert_frame_equal(expr, res1r)
  174. tm.assert_frame_equal(expr, res2l)
  175. res1l, res1r = df1.align(df2, join="right")
  176. res2l, res2r = df2.align(df1, join="left")
  177. exp_idx = pd.MultiIndex.from_product(
  178. [range(2), range(2), range(2)], names=("a", "b", "c")
  179. )
  180. expl = DataFrame([0, 1, 2, 3, 6, 7, 8, 9], index=exp_idx)
  181. tm.assert_frame_equal(expl, res1l)
  182. tm.assert_frame_equal(expl, res2r)
  183. expr = DataFrame([0, 0, 1, 1] * 2, index=exp_idx)
  184. tm.assert_frame_equal(expr, res1r)
  185. tm.assert_frame_equal(expr, res2l)
  186. def test_align_series_combinations(self):
  187. df = DataFrame({"a": [1, 3, 5], "b": [1, 3, 5]}, index=list("ACE"))
  188. s = Series([1, 2, 4], index=list("ABD"), name="x")
  189. # frame + series
  190. res1, res2 = df.align(s, axis=0)
  191. exp1 = DataFrame(
  192. {"a": [1, np.nan, 3, np.nan, 5], "b": [1, np.nan, 3, np.nan, 5]},
  193. index=list("ABCDE"),
  194. )
  195. exp2 = Series([1, 2, np.nan, 4, np.nan], index=list("ABCDE"), name="x")
  196. tm.assert_frame_equal(res1, exp1)
  197. tm.assert_series_equal(res2, exp2)
  198. # series + frame
  199. res1, res2 = s.align(df)
  200. tm.assert_series_equal(res1, exp2)
  201. tm.assert_frame_equal(res2, exp1)
  202. def test_multiindex_align_to_series_with_common_index_level(self):
  203. # GH-46001
  204. foo_index = Index([1, 2, 3], name="foo")
  205. bar_index = Index([1, 2], name="bar")
  206. series = Series([1, 2], index=bar_index, name="foo_series")
  207. df = DataFrame(
  208. {"col": np.arange(6)},
  209. index=pd.MultiIndex.from_product([foo_index, bar_index]),
  210. )
  211. expected_r = Series([1, 2] * 3, index=df.index, name="foo_series")
  212. result_l, result_r = df.align(series, axis=0)
  213. tm.assert_frame_equal(result_l, df)
  214. tm.assert_series_equal(result_r, expected_r)
  215. def test_multiindex_align_to_series_with_common_index_level_missing_in_left(self):
  216. # GH-46001
  217. foo_index = Index([1, 2, 3], name="foo")
  218. bar_index = Index([1, 2], name="bar")
  219. series = Series(
  220. [1, 2, 3, 4], index=Index([1, 2, 3, 4], name="bar"), name="foo_series"
  221. )
  222. df = DataFrame(
  223. {"col": np.arange(6)},
  224. index=pd.MultiIndex.from_product([foo_index, bar_index]),
  225. )
  226. expected_r = Series([1, 2] * 3, index=df.index, name="foo_series")
  227. result_l, result_r = df.align(series, axis=0)
  228. tm.assert_frame_equal(result_l, df)
  229. tm.assert_series_equal(result_r, expected_r)
  230. def test_multiindex_align_to_series_with_common_index_level_missing_in_right(self):
  231. # GH-46001
  232. foo_index = Index([1, 2, 3], name="foo")
  233. bar_index = Index([1, 2, 3, 4], name="bar")
  234. series = Series([1, 2], index=Index([1, 2], name="bar"), name="foo_series")
  235. df = DataFrame(
  236. {"col": np.arange(12)},
  237. index=pd.MultiIndex.from_product([foo_index, bar_index]),
  238. )
  239. expected_r = Series(
  240. [1, 2, np.nan, np.nan] * 3, index=df.index, name="foo_series"
  241. )
  242. result_l, result_r = df.align(series, axis=0)
  243. tm.assert_frame_equal(result_l, df)
  244. tm.assert_series_equal(result_r, expected_r)
  245. def test_multiindex_align_to_series_with_common_index_level_missing_in_both(self):
  246. # GH-46001
  247. foo_index = Index([1, 2, 3], name="foo")
  248. bar_index = Index([1, 3, 4], name="bar")
  249. series = Series(
  250. [1, 2, 3], index=Index([1, 2, 4], name="bar"), name="foo_series"
  251. )
  252. df = DataFrame(
  253. {"col": np.arange(9)},
  254. index=pd.MultiIndex.from_product([foo_index, bar_index]),
  255. )
  256. expected_r = Series([1, np.nan, 3] * 3, index=df.index, name="foo_series")
  257. result_l, result_r = df.align(series, axis=0)
  258. tm.assert_frame_equal(result_l, df)
  259. tm.assert_series_equal(result_r, expected_r)
  260. def test_multiindex_align_to_series_with_common_index_level_non_unique_cols(self):
  261. # GH-46001
  262. foo_index = Index([1, 2, 3], name="foo")
  263. bar_index = Index([1, 2], name="bar")
  264. series = Series([1, 2], index=bar_index, name="foo_series")
  265. df = DataFrame(
  266. np.arange(18).reshape(6, 3),
  267. index=pd.MultiIndex.from_product([foo_index, bar_index]),
  268. )
  269. df.columns = ["cfoo", "cbar", "cfoo"]
  270. expected = Series([1, 2] * 3, index=df.index, name="foo_series")
  271. result_left, result_right = df.align(series, axis=0)
  272. tm.assert_series_equal(result_right, expected)
  273. tm.assert_index_equal(result_left.columns, df.columns)
  274. def test_missing_axis_specification_exception(self):
  275. df = DataFrame(np.arange(50).reshape((10, 5)))
  276. series = Series(np.arange(5))
  277. with pytest.raises(ValueError, match=r"axis=0 or 1"):
  278. df.align(series)
  279. def _check_align(self, a, b, axis, fill_axis, how, method, limit=None):
  280. aa, ab = a.align(
  281. b, axis=axis, join=how, method=method, limit=limit, fill_axis=fill_axis
  282. )
  283. join_index, join_columns = None, None
  284. ea, eb = a, b
  285. if axis is None or axis == 0:
  286. join_index = a.index.join(b.index, how=how)
  287. ea = ea.reindex(index=join_index)
  288. eb = eb.reindex(index=join_index)
  289. if axis is None or axis == 1:
  290. join_columns = a.columns.join(b.columns, how=how)
  291. ea = ea.reindex(columns=join_columns)
  292. eb = eb.reindex(columns=join_columns)
  293. ea = ea.fillna(axis=fill_axis, method=method, limit=limit)
  294. eb = eb.fillna(axis=fill_axis, method=method, limit=limit)
  295. tm.assert_frame_equal(aa, ea)
  296. tm.assert_frame_equal(ab, eb)
  297. @pytest.mark.parametrize("meth", ["pad", "bfill"])
  298. @pytest.mark.parametrize("ax", [0, 1, None])
  299. @pytest.mark.parametrize("fax", [0, 1])
  300. @pytest.mark.parametrize("how", ["inner", "outer", "left", "right"])
  301. def test_align_fill_method(self, how, meth, ax, fax, float_frame):
  302. df = float_frame
  303. self._check_align_fill(df, how, meth, ax, fax)
  304. def _check_align_fill(self, frame, kind, meth, ax, fax):
  305. left = frame.iloc[0:4, :10]
  306. right = frame.iloc[2:, 6:]
  307. empty = frame.iloc[:0, :0]
  308. self._check_align(left, right, axis=ax, fill_axis=fax, how=kind, method=meth)
  309. self._check_align(
  310. left, right, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1
  311. )
  312. # empty left
  313. self._check_align(empty, right, axis=ax, fill_axis=fax, how=kind, method=meth)
  314. self._check_align(
  315. empty, right, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1
  316. )
  317. # empty right
  318. self._check_align(left, empty, axis=ax, fill_axis=fax, how=kind, method=meth)
  319. self._check_align(
  320. left, empty, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1
  321. )
  322. # both empty
  323. self._check_align(empty, empty, axis=ax, fill_axis=fax, how=kind, method=meth)
  324. self._check_align(
  325. empty, empty, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1
  326. )
  327. def test_align_series_check_copy(self):
  328. # GH#
  329. df = DataFrame({0: [1, 2]})
  330. ser = Series([1], name=0)
  331. expected = ser.copy()
  332. result, other = df.align(ser, axis=1)
  333. ser.iloc[0] = 100
  334. tm.assert_series_equal(other, expected)
  335. def test_align_identical_different_object(self):
  336. # GH#51032
  337. df = DataFrame({"a": [1, 2]})
  338. ser = Series([3, 4])
  339. result, result2 = df.align(ser, axis=0)
  340. tm.assert_frame_equal(result, df)
  341. tm.assert_series_equal(result2, ser)
  342. assert df is not result
  343. assert ser is not result2
  344. def test_align_identical_different_object_columns(self):
  345. # GH#51032
  346. df = DataFrame({"a": [1, 2]})
  347. ser = Series([1], index=["a"])
  348. result, result2 = df.align(ser, axis=1)
  349. tm.assert_frame_equal(result, df)
  350. tm.assert_series_equal(result2, ser)
  351. assert df is not result
  352. assert ser is not result2