forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtest_tile.py
310 lines (231 loc) · 10.5 KB
/
test_tile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import os
import nose
import numpy as np
from pandas.compat import zip
from pandas import (DataFrame, Series, unique, Index, Categorical, CategoricalIndex,
DatetimeIndex, TimedeltaIndex)
import pandas.util.testing as tm
from pandas.util.testing import assertRaisesRegexp
import pandas.core.common as com
from pandas.core.algorithms import quantile
from pandas.tools.tile import cut, qcut
import pandas.tools.tile as tmod
from numpy.testing import assert_equal, assert_almost_equal
class TestCut(tm.TestCase):
def test_simple(self):
data = np.ones(5)
result = cut(data, 4, labels=False)
desired = [1, 1, 1, 1, 1]
assert_equal(result, desired)
def test_bins(self):
data = np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1])
result, bins = cut(data, 3, retbins=True)
assert_equal(result.codes, [0, 0, 0, 1, 2, 0])
assert_almost_equal(bins, [0.1905, 3.36666667, 6.53333333, 9.7])
def test_right(self):
data = np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1, 2.575])
result, bins = cut(data, 4, right=True, retbins=True)
assert_equal(result.codes, [0, 0, 0, 2, 3, 0, 0])
assert_almost_equal(bins, [0.1905, 2.575, 4.95, 7.325, 9.7])
def test_noright(self):
data = np.array([.2, 1.4, 2.5, 6.2, 9.7, 2.1, 2.575])
result, bins = cut(data, 4, right=False, retbins=True)
assert_equal(result.codes, [0, 0, 0, 2, 3, 0, 1])
assert_almost_equal(bins, [0.2, 2.575, 4.95, 7.325, 9.7095])
def test_arraylike(self):
data = [.2, 1.4, 2.5, 6.2, 9.7, 2.1]
result, bins = cut(data, 3, retbins=True)
assert_equal(result.codes, [0, 0, 0, 1, 2, 0])
assert_almost_equal(bins, [0.1905, 3.36666667, 6.53333333, 9.7])
def test_bins_not_monotonic(self):
data = [.2, 1.4, 2.5, 6.2, 9.7, 2.1]
self.assertRaises(ValueError, cut, data, [0.1, 1.5, 1, 10])
def test_wrong_num_labels(self):
data = [.2, 1.4, 2.5, 6.2, 9.7, 2.1]
self.assertRaises(ValueError, cut, data, [0, 1, 10],
labels=['foo', 'bar', 'baz'])
def test_cut_corner(self):
# h3h
self.assertRaises(ValueError, cut, [], 2)
self.assertRaises(ValueError, cut, [1, 2, 3], 0.5)
def test_cut_out_of_range_more(self):
# #1511
s = Series([0, -1, 0, 1, -3])
ind = cut(s, [0, 1], labels=False)
exp = [np.nan, np.nan, np.nan, 0, np.nan]
assert_almost_equal(ind, exp)
def test_labels(self):
arr = np.tile(np.arange(0, 1.01, 0.1), 4)
result, bins = cut(arr, 4, retbins=True)
ex_levels = ['(-0.001, 0.25]', '(0.25, 0.5]', '(0.5, 0.75]',
'(0.75, 1]']
self.assert_numpy_array_equal(result.categories, ex_levels)
result, bins = cut(arr, 4, retbins=True, right=False)
ex_levels = ['[0, 0.25)', '[0.25, 0.5)', '[0.5, 0.75)',
'[0.75, 1.001)']
self.assert_numpy_array_equal(result.categories, ex_levels)
def test_cut_pass_series_name_to_factor(self):
s = Series(np.random.randn(100), name='foo')
factor = cut(s, 4)
self.assertEqual(factor.name, 'foo')
def test_label_precision(self):
arr = np.arange(0, 0.73, 0.01)
result = cut(arr, 4, precision=2)
ex_levels = ['(-0.00072, 0.18]', '(0.18, 0.36]', '(0.36, 0.54]',
'(0.54, 0.72]']
self.assert_numpy_array_equal(result.categories, ex_levels)
def test_label_coercion(self):
# GH10140
df = DataFrame({'x' : 100 * np.random.random(100)})
df['y'] = df.x**2
binedges = np.arange(0,110,10)
binlabels = np.arange(5,105,10)
# passing in an index
for bl, expected in [(Index(binlabels), np.dtype('int64')),
(DatetimeIndex(['20130101']*len(binlabels))+TimedeltaIndex(binlabels,unit='D'),np.dtype('M8[ns]')),
(TimedeltaIndex(binlabels,unit='D'),np.dtype('m8[ns]')),
(Categorical(binlabels), 'category'),
(Index(Index(binlabels).map(str)), 'category')]:
result = cut(df.x, bins=binedges, labels=bl)
self.assertEqual(result.dtype, expected)
z = df.groupby(result).y.mean()
self.assertEqual(z.index.dtype, expected)
# passing in a list-like
for bl, expected in [(Index(binlabels), np.dtype('int64')),
(Index(Index(binlabels).map(str)), 'category')]:
bl = np.asarray(bl)
result = cut(df.x, bins=binedges, labels=bl)
self.assertEqual(result.dtype, expected)
z = df.groupby(result).y.mean()
self.assertEqual(z.index.dtype, expected)
# reversed categories
bl = Categorical(binlabels,categories=binlabels[::-1],ordered=True)
expected = Index(bl).dtype
result = cut(df.x, bins=binedges, labels=bl)
self.assertEqual(result.dtype, expected)
z = df.groupby(result).y.mean()
self.assertEqual(z.index.dtype, expected)
tm.assert_index_equal(z.index,
CategoricalIndex(Categorical.from_codes(np.arange(len(bl)),categories=bl.categories,ordered=True),name='x'))
def test_na_handling(self):
arr = np.arange(0, 0.75, 0.01)
arr[::3] = np.nan
result = cut(arr, 4)
result_arr = np.asarray(result)
ex_arr = np.where(com.isnull(arr), np.nan, result_arr)
tm.assert_almost_equal(result_arr, ex_arr)
result = cut(arr, 4, labels=False)
ex_result = np.where(com.isnull(arr), np.nan, result)
tm.assert_almost_equal(result, ex_result)
def test_inf_handling(self):
data = np.arange(6)
data_ser = Series(data,dtype='int64')
result = cut(data, [-np.inf, 2, 4, np.inf])
result_ser = cut(data_ser, [-np.inf, 2, 4, np.inf])
ex_categories = ['(-inf, 2]', '(2, 4]', '(4, inf]']
np.testing.assert_array_equal(result.categories, ex_categories)
np.testing.assert_array_equal(result_ser.cat.categories, ex_categories)
self.assertEqual(result[5], '(4, inf]')
self.assertEqual(result[0], '(-inf, 2]')
self.assertEqual(result_ser[5], '(4, inf]')
self.assertEqual(result_ser[0], '(-inf, 2]')
def test_qcut(self):
arr = np.random.randn(1000)
labels, bins = qcut(arr, 4, retbins=True)
ex_bins = quantile(arr, [0, .25, .5, .75, 1.])
assert_almost_equal(bins, ex_bins)
ex_levels = cut(arr, ex_bins, include_lowest=True)
self.assert_numpy_array_equal(labels, ex_levels)
def test_qcut_bounds(self):
arr = np.random.randn(1000)
factor = qcut(arr, 10, labels=False)
self.assertEqual(len(np.unique(factor)), 10)
def test_qcut_specify_quantiles(self):
arr = np.random.randn(100)
factor = qcut(arr, [0, .25, .5, .75, 1.])
expected = qcut(arr, 4)
self.assertTrue(factor.equals(expected))
def test_qcut_all_bins_same(self):
assertRaisesRegexp(ValueError, "edges.*unique", qcut, [0,0,0,0,0,0,0,0,0,0], 3)
def test_cut_out_of_bounds(self):
arr = np.random.randn(100)
result = cut(arr, [-1, 0, 1])
mask = result.codes == -1
ex_mask = (arr < -1) | (arr > 1)
self.assert_numpy_array_equal(mask, ex_mask)
def test_cut_pass_labels(self):
arr = [50, 5, 10, 15, 20, 30, 70]
bins = [0, 25, 50, 100]
labels = ['Small', 'Medium', 'Large']
result = cut(arr, bins, labels=labels)
exp = cut(arr, bins)
exp.categories = labels
self.assertTrue(result.equals(exp))
def test_qcut_include_lowest(self):
values = np.arange(10)
cats = qcut(values, 4)
ex_levels = ['[0, 2.25]', '(2.25, 4.5]', '(4.5, 6.75]', '(6.75, 9]']
self.assertTrue((cats.categories == ex_levels).all())
def test_qcut_nas(self):
arr = np.random.randn(100)
arr[:20] = np.nan
result = qcut(arr, 4)
self.assertTrue(com.isnull(result[:20]).all())
def test_label_formatting(self):
self.assertEqual(tmod._trim_zeros('1.000'), '1')
# it works
result = cut(np.arange(11.), 2)
result = cut(np.arange(11.) / 1e10, 2)
# #1979, negative numbers
result = tmod._format_label(-117.9998, precision=3)
self.assertEqual(result, '-118')
result = tmod._format_label(117.9998, precision=3)
self.assertEqual(result, '118')
def test_qcut_binning_issues(self):
# #1978, 1979
path = os.path.join(curpath(), 'cut_data.csv')
arr = np.loadtxt(path)
result = qcut(arr, 20)
starts = []
ends = []
for lev in result.categories:
s, e = lev[1:-1].split(',')
self.assertTrue(s != e)
starts.append(float(s))
ends.append(float(e))
for (sp, sn), (ep, en) in zip(zip(starts[:-1], starts[1:]),
zip(ends[:-1], ends[1:])):
self.assertTrue(sp < sn)
self.assertTrue(ep < en)
self.assertTrue(ep <= sn)
def test_cut_return_categorical(self):
from pandas import Categorical
s = Series([0,1,2,3,4,5,6,7,8])
res = cut(s,3)
exp = Series(Categorical.from_codes([0,0,0,1,1,1,2,2,2],
["(-0.008, 2.667]", "(2.667, 5.333]", "(5.333, 8]"],
ordered=True))
tm.assert_series_equal(res, exp)
def test_qcut_return_categorical(self):
from pandas import Categorical
s = Series([0,1,2,3,4,5,6,7,8])
res = qcut(s,[0,0.333,0.666,1])
exp = Series(Categorical.from_codes([0,0,0,1,1,1,2,2,2],
["[0, 2.664]", "(2.664, 5.328]", "(5.328, 8]"],
ordered=True))
tm.assert_series_equal(res, exp)
def test_series_retbins(self):
# GH 8589
s = Series(np.arange(4))
result, bins = cut(s, 2, retbins=True)
assert_equal(result.cat.codes.values, [0, 0, 1, 1])
assert_almost_equal(bins, [-0.003, 1.5, 3])
result, bins = qcut(s, 2, retbins=True)
assert_equal(result.cat.codes.values, [0, 0, 1, 1])
assert_almost_equal(bins, [0, 1.5, 3])
def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))
return pth
if __name__ == '__main__':
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
exit=False)