test_frame.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. from copy import deepcopy
  2. from operator import methodcaller
  3. import numpy as np
  4. import pytest
  5. import pandas as pd
  6. from pandas import (
  7. DataFrame,
  8. MultiIndex,
  9. Series,
  10. date_range,
  11. )
  12. import pandas._testing as tm
  13. class TestDataFrame:
  14. @pytest.mark.parametrize("func", ["_set_axis_name", "rename_axis"])
  15. def test_set_axis_name(self, func):
  16. df = DataFrame([[1, 2], [3, 4]])
  17. result = methodcaller(func, "foo")(df)
  18. assert df.index.name is None
  19. assert result.index.name == "foo"
  20. result = methodcaller(func, "cols", axis=1)(df)
  21. assert df.columns.name is None
  22. assert result.columns.name == "cols"
  23. @pytest.mark.parametrize("func", ["_set_axis_name", "rename_axis"])
  24. def test_set_axis_name_mi(self, func):
  25. df = DataFrame(
  26. np.empty((3, 3)),
  27. index=MultiIndex.from_tuples([("A", x) for x in list("aBc")]),
  28. columns=MultiIndex.from_tuples([("C", x) for x in list("xyz")]),
  29. )
  30. level_names = ["L1", "L2"]
  31. result = methodcaller(func, level_names)(df)
  32. assert result.index.names == level_names
  33. assert result.columns.names == [None, None]
  34. result = methodcaller(func, level_names, axis=1)(df)
  35. assert result.columns.names == ["L1", "L2"]
  36. assert result.index.names == [None, None]
  37. def test_nonzero_single_element(self):
  38. # allow single item via bool method
  39. df = DataFrame([[True]])
  40. assert df.bool()
  41. df = DataFrame([[False]])
  42. assert not df.bool()
  43. df = DataFrame([[False, False]])
  44. msg = "The truth value of a DataFrame is ambiguous"
  45. with pytest.raises(ValueError, match=msg):
  46. df.bool()
  47. with pytest.raises(ValueError, match=msg):
  48. bool(df)
  49. def test_metadata_propagation_indiv_groupby(self):
  50. # groupby
  51. df = DataFrame(
  52. {
  53. "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
  54. "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
  55. "C": np.random.randn(8),
  56. "D": np.random.randn(8),
  57. }
  58. )
  59. result = df.groupby("A").sum()
  60. tm.assert_metadata_equivalent(df, result)
  61. def test_metadata_propagation_indiv_resample(self):
  62. # resample
  63. df = DataFrame(
  64. np.random.randn(1000, 2),
  65. index=date_range("20130101", periods=1000, freq="s"),
  66. )
  67. result = df.resample("1T")
  68. tm.assert_metadata_equivalent(df, result)
  69. def test_metadata_propagation_indiv(self, monkeypatch):
  70. # merging with override
  71. # GH 6923
  72. def finalize(self, other, method=None, **kwargs):
  73. for name in self._metadata:
  74. if method == "merge":
  75. left, right = other.left, other.right
  76. value = getattr(left, name, "") + "|" + getattr(right, name, "")
  77. object.__setattr__(self, name, value)
  78. elif method == "concat":
  79. value = "+".join(
  80. [getattr(o, name) for o in other.objs if getattr(o, name, None)]
  81. )
  82. object.__setattr__(self, name, value)
  83. else:
  84. object.__setattr__(self, name, getattr(other, name, ""))
  85. return self
  86. with monkeypatch.context() as m:
  87. m.setattr(DataFrame, "_metadata", ["filename"])
  88. m.setattr(DataFrame, "__finalize__", finalize)
  89. np.random.seed(10)
  90. df1 = DataFrame(np.random.randint(0, 4, (3, 2)), columns=["a", "b"])
  91. df2 = DataFrame(np.random.randint(0, 4, (3, 2)), columns=["c", "d"])
  92. DataFrame._metadata = ["filename"]
  93. df1.filename = "fname1.csv"
  94. df2.filename = "fname2.csv"
  95. result = df1.merge(df2, left_on=["a"], right_on=["c"], how="inner")
  96. assert result.filename == "fname1.csv|fname2.csv"
  97. # concat
  98. # GH#6927
  99. df1 = DataFrame(np.random.randint(0, 4, (3, 2)), columns=list("ab"))
  100. df1.filename = "foo"
  101. result = pd.concat([df1, df1])
  102. assert result.filename == "foo+foo"
  103. def test_set_attribute(self):
  104. # Test for consistent setattr behavior when an attribute and a column
  105. # have the same name (Issue #8994)
  106. df = DataFrame({"x": [1, 2, 3]})
  107. df.y = 2
  108. df["y"] = [2, 4, 6]
  109. df.y = 5
  110. assert df.y == 5
  111. tm.assert_series_equal(df["y"], Series([2, 4, 6], name="y"))
  112. def test_deepcopy_empty(self):
  113. # This test covers empty frame copying with non-empty column sets
  114. # as reported in issue GH15370
  115. empty_frame = DataFrame(data=[], index=[], columns=["A"])
  116. empty_frame_copy = deepcopy(empty_frame)
  117. tm.assert_frame_equal(empty_frame_copy, empty_frame)
  118. # formerly in Generic but only test DataFrame
  119. class TestDataFrame2:
  120. @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
  121. def test_validate_bool_args(self, value):
  122. df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
  123. msg = 'For argument "inplace" expected type bool, received type'
  124. with pytest.raises(ValueError, match=msg):
  125. df.copy().rename_axis(mapper={"a": "x", "b": "y"}, axis=1, inplace=value)
  126. with pytest.raises(ValueError, match=msg):
  127. df.copy().drop("a", axis=1, inplace=value)
  128. with pytest.raises(ValueError, match=msg):
  129. df.copy().fillna(value=0, inplace=value)
  130. with pytest.raises(ValueError, match=msg):
  131. df.copy().replace(to_replace=1, value=7, inplace=value)
  132. with pytest.raises(ValueError, match=msg):
  133. df.copy().interpolate(inplace=value)
  134. with pytest.raises(ValueError, match=msg):
  135. df.copy()._where(cond=df.a > 2, inplace=value)
  136. with pytest.raises(ValueError, match=msg):
  137. df.copy().mask(cond=df.a > 2, inplace=value)
  138. def test_unexpected_keyword(self):
  139. # GH8597
  140. df = DataFrame(np.random.randn(5, 2), columns=["jim", "joe"])
  141. ca = pd.Categorical([0, 0, 2, 2, 3, np.nan])
  142. ts = df["joe"].copy()
  143. ts[2] = np.nan
  144. msg = "unexpected keyword"
  145. with pytest.raises(TypeError, match=msg):
  146. df.drop("joe", axis=1, in_place=True)
  147. with pytest.raises(TypeError, match=msg):
  148. df.reindex([1, 0], inplace=True)
  149. with pytest.raises(TypeError, match=msg):
  150. ca.fillna(0, inplace=True)
  151. with pytest.raises(TypeError, match=msg):
  152. ts.fillna(0, in_place=True)