test_round.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import numpy as np
  2. import pytest
  3. import pandas as pd
  4. from pandas import Series
  5. import pandas._testing as tm
  6. class TestSeriesRound:
  7. def test_round(self, datetime_series):
  8. datetime_series.index.name = "index_name"
  9. result = datetime_series.round(2)
  10. expected = Series(
  11. np.round(datetime_series.values, 2), index=datetime_series.index, name="ts"
  12. )
  13. tm.assert_series_equal(result, expected)
  14. assert result.name == datetime_series.name
  15. def test_round_numpy(self, any_float_dtype):
  16. # See GH#12600
  17. ser = Series([1.53, 1.36, 0.06], dtype=any_float_dtype)
  18. out = np.round(ser, decimals=0)
  19. expected = Series([2.0, 1.0, 0.0], dtype=any_float_dtype)
  20. tm.assert_series_equal(out, expected)
  21. msg = "the 'out' parameter is not supported"
  22. with pytest.raises(ValueError, match=msg):
  23. np.round(ser, decimals=0, out=ser)
  24. def test_round_numpy_with_nan(self, any_float_dtype):
  25. # See GH#14197
  26. ser = Series([1.53, np.nan, 0.06], dtype=any_float_dtype)
  27. with tm.assert_produces_warning(None):
  28. result = ser.round()
  29. expected = Series([2.0, np.nan, 0.0], dtype=any_float_dtype)
  30. tm.assert_series_equal(result, expected)
  31. def test_round_builtin(self, any_float_dtype):
  32. ser = Series(
  33. [1.123, 2.123, 3.123],
  34. index=range(3),
  35. dtype=any_float_dtype,
  36. )
  37. result = round(ser)
  38. expected_rounded0 = Series(
  39. [1.0, 2.0, 3.0], index=range(3), dtype=any_float_dtype
  40. )
  41. tm.assert_series_equal(result, expected_rounded0)
  42. decimals = 2
  43. expected_rounded = Series(
  44. [1.12, 2.12, 3.12], index=range(3), dtype=any_float_dtype
  45. )
  46. result = round(ser, decimals)
  47. tm.assert_series_equal(result, expected_rounded)
  48. @pytest.mark.parametrize("method", ["round", "floor", "ceil"])
  49. @pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"])
  50. def test_round_nat(self, method, freq, unit):
  51. # GH14940, GH#56158
  52. ser = Series([pd.NaT], dtype=f"M8[{unit}]")
  53. expected = Series(pd.NaT, dtype=f"M8[{unit}]")
  54. round_method = getattr(ser.dt, method)
  55. result = round_method(freq)
  56. tm.assert_series_equal(result, expected)
  57. def test_round_ea_boolean(self):
  58. # GH#55936
  59. ser = Series([True, False], dtype="boolean")
  60. expected = ser.copy()
  61. result = ser.round(2)
  62. tm.assert_series_equal(result, expected)
  63. result.iloc[0] = False
  64. tm.assert_series_equal(ser, expected)
  65. def test_round_dtype_object(self):
  66. # GH#61206
  67. ser = Series([0.2], dtype="object")
  68. msg = "Expected numeric dtype, got object instead."
  69. with pytest.raises(TypeError, match=msg):
  70. ser.round()