forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest_period.py
302 lines (231 loc) · 9.2 KB
/
test_period.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
import numpy as np
import pytest
from pandas._libs.tslibs import iNaT
from pandas._libs.tslibs.period import IncompatibleFrequency
from pandas.core.dtypes.dtypes import PeriodDtype, registry
import pandas as pd
from pandas.core.arrays import PeriodArray, period_array
import pandas.util.testing as tm
# ----------------------------------------------------------------------------
# Dtype
def test_registered():
assert PeriodDtype in registry.dtypes
result = registry.find("Period[D]")
expected = PeriodDtype("D")
assert result == expected
# ----------------------------------------------------------------------------
# period_array
@pytest.mark.parametrize("data, freq, expected", [
([pd.Period("2017", "D")], None, [17167]),
([pd.Period("2017", "D")], "D", [17167]),
([2017], "D", [17167]),
(["2017"], "D", [17167]),
([pd.Period("2017", "D")], pd.tseries.offsets.Day(), [17167]),
([pd.Period("2017", "D"), None], None, [17167, iNaT]),
(pd.Series(pd.date_range("2017", periods=3)), None,
[17167, 17168, 17169]),
(pd.date_range("2017", periods=3), None, [17167, 17168, 17169]),
])
def test_period_array_ok(data, freq, expected):
result = period_array(data, freq=freq).asi8
expected = np.asarray(expected, dtype=np.int64)
tm.assert_numpy_array_equal(result, expected)
def test_from_datetime64_freq_changes():
# https://github.com/pandas-dev/pandas/issues/23438
arr = pd.date_range("2017", periods=3, freq="D")
result = PeriodArray._from_datetime64(arr, freq="M")
expected = period_array(['2017-01-01', '2017-01-01', '2017-01-01'],
freq="M")
tm.assert_period_array_equal(result, expected)
@pytest.mark.parametrize("data, freq, msg", [
([pd.Period('2017', 'D'),
pd.Period('2017', 'A')],
None,
"Input has different freq"),
([pd.Period('2017', 'D')],
"A",
"Input has different freq"),
])
def test_period_array_raises(data, freq, msg):
with pytest.raises(IncompatibleFrequency, match=msg):
period_array(data, freq)
def test_period_array_non_period_series_raies():
ser = pd.Series([1, 2, 3])
with pytest.raises(TypeError, match='dtype'):
PeriodArray(ser, freq='D')
def test_period_array_freq_mismatch():
arr = period_array(['2000', '2001'], freq='D')
with pytest.raises(IncompatibleFrequency, match='freq'):
PeriodArray(arr, freq='M')
with pytest.raises(IncompatibleFrequency, match='freq'):
PeriodArray(arr, freq=pd.tseries.offsets.MonthEnd())
def test_asi8():
result = period_array(['2000', '2001', None], freq='D').asi8
expected = np.array([10957, 11323, iNaT])
tm.assert_numpy_array_equal(result, expected)
def test_take_raises():
arr = period_array(['2000', '2001'], freq='D')
with pytest.raises(IncompatibleFrequency, match='freq'):
arr.take([0, -1], allow_fill=True,
fill_value=pd.Period('2000', freq='W'))
with pytest.raises(ValueError, match='foo'):
arr.take([0, -1], allow_fill=True, fill_value='foo')
@pytest.mark.parametrize('dtype', [
int, np.int32, np.int64, 'uint32', 'uint64',
])
def test_astype(dtype):
# We choose to ignore the sign and size of integers for
# Period/Datetime/Timedelta astype
arr = period_array(['2000', '2001', None], freq='D')
result = arr.astype(dtype)
if np.dtype(dtype).kind == 'u':
expected_dtype = np.dtype('uint64')
else:
expected_dtype = np.dtype('int64')
expected = arr.astype(expected_dtype)
assert result.dtype == expected_dtype
tm.assert_numpy_array_equal(result, expected)
def test_astype_copies():
arr = period_array(['2000', '2001', None], freq='D')
result = arr.astype(np.int64, copy=False)
# Add the `.base`, since we now use `.asi8` which returns a view.
# We could maybe override it in PeriodArray to return ._data directly.
assert result.base is arr._data
result = arr.astype(np.int64, copy=True)
assert result is not arr._data
tm.assert_numpy_array_equal(result, arr._data.view('i8'))
def test_astype_categorical():
arr = period_array(['2000', '2001', '2001', None], freq='D')
result = arr.astype('category')
categories = pd.PeriodIndex(['2000', '2001'], freq='D')
expected = pd.Categorical.from_codes([0, 1, 1, -1], categories=categories)
tm.assert_categorical_equal(result, expected)
def test_astype_period():
arr = period_array(['2000', '2001', None], freq='D')
result = arr.astype(PeriodDtype("M"))
expected = period_array(['2000', '2001', None], freq='M')
tm.assert_period_array_equal(result, expected)
@pytest.mark.parametrize('other', [
'datetime64[ns]', 'timedelta64[ns]',
])
def test_astype_datetime(other):
arr = period_array(['2000', '2001', None], freq='D')
# slice off the [ns] so that the regex matches.
with pytest.raises(TypeError, match=other[:-4]):
arr.astype(other)
def test_fillna_raises():
arr = period_array(['2000', '2001', '2002'], freq='D')
with pytest.raises(ValueError, match='Length'):
arr.fillna(arr[:2])
def test_fillna_copies():
arr = period_array(['2000', '2001', '2002'], freq='D')
result = arr.fillna(pd.Period("2000", "D"))
assert result is not arr
# ----------------------------------------------------------------------------
# setitem
@pytest.mark.parametrize('key, value, expected', [
([0], pd.Period("2000", "D"), [10957, 1, 2]),
([0], None, [iNaT, 1, 2]),
([0], np.nan, [iNaT, 1, 2]),
([0, 1, 2], pd.Period("2000", "D"), [10957] * 3),
([0, 1, 2], [pd.Period("2000", "D"),
pd.Period("2001", "D"),
pd.Period("2002", "D")],
[10957, 11323, 11688]),
])
def test_setitem(key, value, expected):
arr = PeriodArray(np.arange(3), freq="D")
expected = PeriodArray(expected, freq="D")
arr[key] = value
tm.assert_period_array_equal(arr, expected)
def test_setitem_raises_incompatible_freq():
arr = PeriodArray(np.arange(3), freq="D")
with pytest.raises(IncompatibleFrequency, match="freq"):
arr[0] = pd.Period("2000", freq="A")
other = period_array(['2000', '2001'], freq='A')
with pytest.raises(IncompatibleFrequency, match="freq"):
arr[[0, 1]] = other
def test_setitem_raises_length():
arr = PeriodArray(np.arange(3), freq="D")
with pytest.raises(ValueError, match="length"):
arr[[0, 1]] = [pd.Period("2000", freq="D")]
def test_setitem_raises_type():
arr = PeriodArray(np.arange(3), freq="D")
with pytest.raises(TypeError, match="int"):
arr[0] = 1
# ----------------------------------------------------------------------------
# Ops
def test_sub_period():
arr = period_array(['2000', '2001'], freq='D')
other = pd.Period("2000", freq="M")
with pytest.raises(IncompatibleFrequency, match="freq"):
arr - other
# ----------------------------------------------------------------------------
# Methods
@pytest.mark.parametrize('other', [
pd.Period('2000', freq='H'),
period_array(['2000', '2001', '2000'], freq='H')
])
def test_where_different_freq_raises(other):
ser = pd.Series(period_array(['2000', '2001', '2002'], freq='D'))
cond = np.array([True, False, True])
with pytest.raises(IncompatibleFrequency,
match="Input has different freq=H"):
ser.where(cond, other)
# ----------------------------------------------------------------------------
# Printing
def test_repr_small():
arr = period_array(['2000', '2001'], freq='D')
result = str(arr)
expected = (
"<PeriodArray>\n"
"['2000-01-01', '2001-01-01']\n"
"Length: 2, dtype: period[D]"
)
assert result == expected
def test_repr_large():
arr = period_array(['2000', '2001'] * 500, freq='D')
result = str(arr)
expected = (
"<PeriodArray>\n"
"['2000-01-01', '2001-01-01', '2000-01-01', '2001-01-01', "
"'2000-01-01',\n"
" '2001-01-01', '2000-01-01', '2001-01-01', '2000-01-01', "
"'2001-01-01',\n"
" ...\n"
" '2000-01-01', '2001-01-01', '2000-01-01', '2001-01-01', "
"'2000-01-01',\n"
" '2001-01-01', '2000-01-01', '2001-01-01', '2000-01-01', "
"'2001-01-01']\n"
"Length: 1000, dtype: period[D]"
)
assert result == expected
# ----------------------------------------------------------------------------
# Reductions
class TestReductions(object):
def test_min_max(self):
arr = period_array([
'2000-01-03',
'2000-01-03',
'NaT',
'2000-01-02',
'2000-01-05',
'2000-01-04',
], freq='D')
result = arr.min()
expected = pd.Period('2000-01-02', freq='D')
assert result == expected
result = arr.max()
expected = pd.Period('2000-01-05', freq='D')
assert result == expected
result = arr.min(skipna=False)
assert result is pd.NaT
result = arr.max(skipna=False)
assert result is pd.NaT
@pytest.mark.parametrize('skipna', [True, False])
def test_min_max_empty(self, skipna):
arr = period_array([], freq='D')
result = arr.min(skipna=skipna)
assert result is pd.NaT
result = arr.max(skipna=skipna)
assert result is pd.NaT