test_aggregation.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import numpy as np
  2. import pytest
  3. from pandas.core.aggregation import (
  4. _make_unique_kwarg_list,
  5. maybe_mangle_lambdas,
  6. )
  7. def test_maybe_mangle_lambdas_passthrough():
  8. assert maybe_mangle_lambdas("mean") == "mean"
  9. assert maybe_mangle_lambdas(lambda x: x).__name__ == "<lambda>"
  10. # don't mangel single lambda.
  11. assert maybe_mangle_lambdas([lambda x: x])[0].__name__ == "<lambda>"
  12. def test_maybe_mangle_lambdas_listlike():
  13. aggfuncs = [lambda x: 1, lambda x: 2]
  14. result = maybe_mangle_lambdas(aggfuncs)
  15. assert result[0].__name__ == "<lambda_0>"
  16. assert result[1].__name__ == "<lambda_1>"
  17. assert aggfuncs[0](None) == result[0](None)
  18. assert aggfuncs[1](None) == result[1](None)
  19. def test_maybe_mangle_lambdas():
  20. func = {"A": [lambda x: 0, lambda x: 1]}
  21. result = maybe_mangle_lambdas(func)
  22. assert result["A"][0].__name__ == "<lambda_0>"
  23. assert result["A"][1].__name__ == "<lambda_1>"
  24. def test_maybe_mangle_lambdas_args():
  25. func = {"A": [lambda x, a, b=1: (0, a, b), lambda x: 1]}
  26. result = maybe_mangle_lambdas(func)
  27. assert result["A"][0].__name__ == "<lambda_0>"
  28. assert result["A"][1].__name__ == "<lambda_1>"
  29. assert func["A"][0](0, 1) == (0, 1, 1)
  30. assert func["A"][0](0, 1, 2) == (0, 1, 2)
  31. assert func["A"][0](0, 2, b=3) == (0, 2, 3)
  32. def test_maybe_mangle_lambdas_named():
  33. func = {"C": np.mean, "D": {"foo": np.mean, "bar": np.mean}}
  34. result = maybe_mangle_lambdas(func)
  35. assert result == func
  36. @pytest.mark.parametrize(
  37. "order, expected_reorder",
  38. [
  39. (
  40. [
  41. ("height", "<lambda>"),
  42. ("height", "max"),
  43. ("weight", "max"),
  44. ("height", "<lambda>"),
  45. ("weight", "<lambda>"),
  46. ],
  47. [
  48. ("height", "<lambda>_0"),
  49. ("height", "max"),
  50. ("weight", "max"),
  51. ("height", "<lambda>_1"),
  52. ("weight", "<lambda>"),
  53. ],
  54. ),
  55. (
  56. [
  57. ("col2", "min"),
  58. ("col1", "<lambda>"),
  59. ("col1", "<lambda>"),
  60. ("col1", "<lambda>"),
  61. ],
  62. [
  63. ("col2", "min"),
  64. ("col1", "<lambda>_0"),
  65. ("col1", "<lambda>_1"),
  66. ("col1", "<lambda>_2"),
  67. ],
  68. ),
  69. (
  70. [("col", "<lambda>"), ("col", "<lambda>"), ("col", "<lambda>")],
  71. [("col", "<lambda>_0"), ("col", "<lambda>_1"), ("col", "<lambda>_2")],
  72. ),
  73. ],
  74. )
  75. def test_make_unique(order, expected_reorder):
  76. # GH 27519, test if make_unique function reorders correctly
  77. result = _make_unique_kwarg_list(order)
  78. assert result == expected_reorder