test_npfuncs.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """
  2. Tests for np.foo applied to DataFrame, not necessarily ufuncs.
  3. """
  4. import numpy as np
  5. from pandas import (
  6. Categorical,
  7. DataFrame,
  8. )
  9. import pandas._testing as tm
  10. class TestAsArray:
  11. def test_asarray_homogeneous(self):
  12. df = DataFrame({"A": Categorical([1, 2]), "B": Categorical([1, 2])})
  13. result = np.asarray(df)
  14. # may change from object in the future
  15. expected = np.array([[1, 1], [2, 2]], dtype="object")
  16. tm.assert_numpy_array_equal(result, expected)
  17. def test_np_sqrt(self, float_frame):
  18. with np.errstate(all="ignore"):
  19. result = np.sqrt(float_frame)
  20. assert isinstance(result, type(float_frame))
  21. assert result.index.is_(float_frame.index)
  22. assert result.columns.is_(float_frame.columns)
  23. tm.assert_frame_equal(result, float_frame.apply(np.sqrt))
  24. def test_sum_deprecated_axis_behavior(self):
  25. # GH#52042 deprecated behavior of df.sum(axis=None), which gets
  26. # called when we do np.sum(df)
  27. arr = np.random.default_rng(2).standard_normal((4, 3))
  28. df = DataFrame(arr)
  29. msg = "The behavior of DataFrame.sum with axis=None is deprecated"
  30. with tm.assert_produces_warning(
  31. FutureWarning, match=msg, check_stacklevel=False
  32. ):
  33. res = np.sum(df)
  34. with tm.assert_produces_warning(FutureWarning, match=msg):
  35. expected = df.sum(axis=None)
  36. tm.assert_series_equal(res, expected)
  37. def test_np_ravel(self):
  38. # GH26247
  39. arr = np.array(
  40. [
  41. [0.11197053, 0.44361564, -0.92589452],
  42. [0.05883648, -0.00948922, -0.26469934],
  43. ]
  44. )
  45. result = np.ravel([DataFrame(batch.reshape(1, 3)) for batch in arr])
  46. expected = np.array(
  47. [
  48. 0.11197053,
  49. 0.44361564,
  50. -0.92589452,
  51. 0.05883648,
  52. -0.00948922,
  53. -0.26469934,
  54. ]
  55. )
  56. tm.assert_numpy_array_equal(result, expected)
  57. result = np.ravel(DataFrame(arr[0].reshape(1, 3), columns=["x1", "x2", "x3"]))
  58. expected = np.array([0.11197053, 0.44361564, -0.92589452])
  59. tm.assert_numpy_array_equal(result, expected)
  60. result = np.ravel(
  61. [
  62. DataFrame(batch.reshape(1, 3), columns=["x1", "x2", "x3"])
  63. for batch in arr
  64. ]
  65. )
  66. expected = np.array(
  67. [
  68. 0.11197053,
  69. 0.44361564,
  70. -0.92589452,
  71. 0.05883648,
  72. -0.00948922,
  73. -0.26469934,
  74. ]
  75. )
  76. tm.assert_numpy_array_equal(result, expected)