/pandas/tools/tests/test_tile.py

http://github.com/wesm/pandas · Python · 282 lines · 204 code · 72 blank · 6 comment · 3 complexity · cdbfbd62d8f89840b08ddec709b00aa3 MD5 · raw file

  1. import os
  2. import nose
  3. import numpy as np
  4. from pandas.compat import zip
  5. from pandas import Series, Index
  6. import pandas.util.testing as tm
  7. from pandas.util.testing import assertRaisesRegexp
  8. import pandas.core.common as com
  9. from pandas.core.algorithms import quantile
  10. from pandas.tools.tile import cut, qcut
  11. import pandas.tools.tile as tmod
  12. class TestCut(tm.TestCase):
  13. def test_simple(self):
  14. data = np.ones(5)
  15. result = cut(data, 4, labels=False)
  16. desired = np.array([1, 1, 1, 1, 1])
  17. tm.assert_numpy_array_equal(result, desired,
  18. check_dtype=False)
  19. def test_bins(self):
  20. data = np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1])
  21. result, bins = cut(data, 3, retbins=True)
  22. exp_codes = np.array([0, 0, 0, 1, 2, 0], dtype=np.int8)
  23. tm.assert_numpy_array_equal(result.codes, exp_codes)
  24. exp = np.array([0.1905, 3.36666667, 6.53333333, 9.7])
  25. tm.assert_almost_equal(bins, exp)
  26. def test_right(self):
  27. data = np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1, 2.575])
  28. result, bins = cut(data, 4, right=True, retbins=True)
  29. exp_codes = np.array([0, 0, 0, 2, 3, 0, 0], dtype=np.int8)
  30. tm.assert_numpy_array_equal(result.codes, exp_codes)
  31. exp = np.array([0.1905, 2.575, 4.95, 7.325, 9.7])
  32. tm.assert_numpy_array_equal(bins, exp)
  33. def test_noright(self):
  34. data = np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1, 2.575])
  35. result, bins = cut(data, 4, right=False, retbins=True)
  36. exp_codes = np.array([0, 0, 0, 2, 3, 0, 1], dtype=np.int8)
  37. tm.assert_numpy_array_equal(result.codes, exp_codes)
  38. exp = np.array([0.2, 2.575, 4.95, 7.325, 9.7095])
  39. tm.assert_almost_equal(bins, exp)
  40. def test_arraylike(self):
  41. data = [.2, 1.4, 2.5, 6.2, 9.7, 2.1]
  42. result, bins = cut(data, 3, retbins=True)
  43. exp_codes = np.array([0, 0, 0, 1, 2, 0], dtype=np.int8)
  44. tm.assert_numpy_array_equal(result.codes, exp_codes)
  45. exp = np.array([0.1905, 3.36666667, 6.53333333, 9.7])
  46. tm.assert_almost_equal(bins, exp)
  47. def test_bins_not_monotonic(self):
  48. data = [.2, 1.4, 2.5, 6.2, 9.7, 2.1]
  49. self.assertRaises(ValueError, cut, data, [0.1, 1.5, 1, 10])
  50. def test_wrong_num_labels(self):
  51. data = [.2, 1.4, 2.5, 6.2, 9.7, 2.1]
  52. self.assertRaises(ValueError, cut, data, [0, 1, 10],
  53. labels=['foo', 'bar', 'baz'])
  54. def test_cut_corner(self):
  55. # h3h
  56. self.assertRaises(ValueError, cut, [], 2)
  57. self.assertRaises(ValueError, cut, [1, 2, 3], 0.5)
  58. def test_cut_out_of_range_more(self):
  59. # #1511
  60. s = Series([0, -1, 0, 1, -3], name='x')
  61. ind = cut(s, [0, 1], labels=False)
  62. exp = Series([np.nan, np.nan, np.nan, 0, np.nan], name='x')
  63. tm.assert_series_equal(ind, exp)
  64. def test_labels(self):
  65. arr = np.tile(np.arange(0, 1.01, 0.1), 4)
  66. result, bins = cut(arr, 4, retbins=True)
  67. ex_levels = Index(['(-0.001, 0.25]', '(0.25, 0.5]', '(0.5, 0.75]',
  68. '(0.75, 1]'])
  69. self.assert_index_equal(result.categories, ex_levels)
  70. result, bins = cut(arr, 4, retbins=True, right=False)
  71. ex_levels = Index(['[0, 0.25)', '[0.25, 0.5)', '[0.5, 0.75)',
  72. '[0.75, 1.001)'])
  73. self.assert_index_equal(result.categories, ex_levels)
  74. def test_cut_pass_series_name_to_factor(self):
  75. s = Series(np.random.randn(100), name='foo')
  76. factor = cut(s, 4)
  77. self.assertEqual(factor.name, 'foo')
  78. def test_label_precision(self):
  79. arr = np.arange(0, 0.73, 0.01)
  80. result = cut(arr, 4, precision=2)
  81. ex_levels = Index(['(-0.00072, 0.18]', '(0.18, 0.36]',
  82. '(0.36, 0.54]', '(0.54, 0.72]'])
  83. self.assert_index_equal(result.categories, ex_levels)
  84. def test_na_handling(self):
  85. arr = np.arange(0, 0.75, 0.01)
  86. arr[::3] = np.nan
  87. result = cut(arr, 4)
  88. result_arr = np.asarray(result)
  89. ex_arr = np.where(com.isnull(arr), np.nan, result_arr)
  90. tm.assert_almost_equal(result_arr, ex_arr)
  91. result = cut(arr, 4, labels=False)
  92. ex_result = np.where(com.isnull(arr), np.nan, result)
  93. tm.assert_almost_equal(result, ex_result)
  94. def test_inf_handling(self):
  95. data = np.arange(6)
  96. data_ser = Series(data, dtype='int64')
  97. result = cut(data, [-np.inf, 2, 4, np.inf])
  98. result_ser = cut(data_ser, [-np.inf, 2, 4, np.inf])
  99. ex_categories = Index(['(-inf, 2]', '(2, 4]', '(4, inf]'])
  100. tm.assert_index_equal(result.categories, ex_categories)
  101. tm.assert_index_equal(result_ser.cat.categories, ex_categories)
  102. self.assertEqual(result[5], '(4, inf]')
  103. self.assertEqual(result[0], '(-inf, 2]')
  104. self.assertEqual(result_ser[5], '(4, inf]')
  105. self.assertEqual(result_ser[0], '(-inf, 2]')
  106. def test_qcut(self):
  107. arr = np.random.randn(1000)
  108. labels, bins = qcut(arr, 4, retbins=True)
  109. ex_bins = quantile(arr, [0, .25, .5, .75, 1.])
  110. tm.assert_almost_equal(bins, ex_bins)
  111. ex_levels = cut(arr, ex_bins, include_lowest=True)
  112. self.assert_categorical_equal(labels, ex_levels)
  113. def test_qcut_bounds(self):
  114. arr = np.random.randn(1000)
  115. factor = qcut(arr, 10, labels=False)
  116. self.assertEqual(len(np.unique(factor)), 10)
  117. def test_qcut_specify_quantiles(self):
  118. arr = np.random.randn(100)
  119. factor = qcut(arr, [0, .25, .5, .75, 1.])
  120. expected = qcut(arr, 4)
  121. tm.assert_categorical_equal(factor, expected)
  122. def test_qcut_all_bins_same(self):
  123. assertRaisesRegexp(ValueError, "edges.*unique", qcut,
  124. [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3)
  125. def test_cut_out_of_bounds(self):
  126. arr = np.random.randn(100)
  127. result = cut(arr, [-1, 0, 1])
  128. mask = result.codes == -1
  129. ex_mask = (arr < -1) | (arr > 1)
  130. self.assert_numpy_array_equal(mask, ex_mask)
  131. def test_cut_pass_labels(self):
  132. arr = [50, 5, 10, 15, 20, 30, 70]
  133. bins = [0, 25, 50, 100]
  134. labels = ['Small', 'Medium', 'Large']
  135. result = cut(arr, bins, labels=labels)
  136. exp = cut(arr, bins)
  137. exp.categories = labels
  138. tm.assert_categorical_equal(result, exp)
  139. def test_qcut_include_lowest(self):
  140. values = np.arange(10)
  141. cats = qcut(values, 4)
  142. ex_levels = ['[0, 2.25]', '(2.25, 4.5]', '(4.5, 6.75]', '(6.75, 9]']
  143. self.assertTrue((cats.categories == ex_levels).all())
  144. def test_qcut_nas(self):
  145. arr = np.random.randn(100)
  146. arr[:20] = np.nan
  147. result = qcut(arr, 4)
  148. self.assertTrue(com.isnull(result[:20]).all())
  149. def test_label_formatting(self):
  150. self.assertEqual(tmod._trim_zeros('1.000'), '1')
  151. # it works
  152. result = cut(np.arange(11.), 2)
  153. result = cut(np.arange(11.) / 1e10, 2)
  154. # #1979, negative numbers
  155. result = tmod._format_label(-117.9998, precision=3)
  156. self.assertEqual(result, '-118')
  157. result = tmod._format_label(117.9998, precision=3)
  158. self.assertEqual(result, '118')
  159. def test_qcut_binning_issues(self):
  160. # #1978, 1979
  161. path = os.path.join(tm.get_data_path(), 'cut_data.csv')
  162. arr = np.loadtxt(path)
  163. result = qcut(arr, 20)
  164. starts = []
  165. ends = []
  166. for lev in result.categories:
  167. s, e = lev[1:-1].split(',')
  168. self.assertTrue(s != e)
  169. starts.append(float(s))
  170. ends.append(float(e))
  171. for (sp, sn), (ep, en) in zip(zip(starts[:-1], starts[1:]),
  172. zip(ends[:-1], ends[1:])):
  173. self.assertTrue(sp < sn)
  174. self.assertTrue(ep < en)
  175. self.assertTrue(ep <= sn)
  176. def test_cut_return_categorical(self):
  177. from pandas import Categorical
  178. s = Series([0, 1, 2, 3, 4, 5, 6, 7, 8])
  179. res = cut(s, 3)
  180. exp = Series(Categorical.from_codes([0, 0, 0, 1, 1, 1, 2, 2, 2],
  181. ["(-0.008, 2.667]",
  182. "(2.667, 5.333]", "(5.333, 8]"],
  183. ordered=True))
  184. tm.assert_series_equal(res, exp)
  185. def test_qcut_return_categorical(self):
  186. from pandas import Categorical
  187. s = Series([0, 1, 2, 3, 4, 5, 6, 7, 8])
  188. res = qcut(s, [0, 0.333, 0.666, 1])
  189. exp = Series(Categorical.from_codes([0, 0, 0, 1, 1, 1, 2, 2, 2],
  190. ["[0, 2.664]",
  191. "(2.664, 5.328]", "(5.328, 8]"],
  192. ordered=True))
  193. tm.assert_series_equal(res, exp)
  194. def test_series_retbins(self):
  195. # GH 8589
  196. s = Series(np.arange(4))
  197. result, bins = cut(s, 2, retbins=True)
  198. tm.assert_numpy_array_equal(result.cat.codes.values,
  199. np.array([0, 0, 1, 1], dtype=np.int8))
  200. tm.assert_numpy_array_equal(bins, np.array([-0.003, 1.5, 3]))
  201. result, bins = qcut(s, 2, retbins=True)
  202. tm.assert_numpy_array_equal(result.cat.codes.values,
  203. np.array([0, 0, 1, 1], dtype=np.int8))
  204. tm.assert_numpy_array_equal(bins, np.array([0, 1.5, 3]))
  205. def curpath():
  206. pth, _ = os.path.split(os.path.abspath(__file__))
  207. return pth
  208. if __name__ == '__main__':
  209. nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
  210. exit=False)