Debian Codegraph @

tests/pandas_test.py

raw ◀ ▶
1 Debian patch touch this file
1 import datetime
2
3 import pytest
4
5 try:
6 import numpy as np
7 import pandas as pd
8 from pandas.testing import (
9 assert_frame_equal,
10 assert_index_equal,
11 assert_series_equal,
12 )
13 except ImportError:
14 pytest.skip('numpy is not available', allow_module_level=True)
15
16
17 import jsonpickle
18 import jsonpickle.ext.pandas
19
20
21 @pytest.fixture(scope='module', autouse=True)
22 def pandas_extension():
23 """Initialize the numpy extension for this test module"""
24 jsonpickle.ext.pandas.register_handlers()
25 yield # control to the test function.
26 jsonpickle.ext.pandas.unregister_handlers()
27
28
29 def roundtrip(obj, **kwargs):
30 return jsonpickle.decode(jsonpickle.encode(obj, **kwargs))
31
32
33 def test_series_roundtrip():
34 ser = pd.Series(
35 {
36 'an_int': np.int_(1),
37 'a_float': np.float64(2.5),
38 'a_nan': np.nan,
39 'a_minus_inf': -np.inf,
40 'an_inf': np.inf,
41 'a_str': np.str_('foo'),
42 'date': np.datetime64('2014-01-01'),
43 'complex': np.complex128(1 - 2j),
44 # TODO: the following dtypes are not currently supported.
45 # 'object': np.object_({'a': 'b'}),
46 }
47 )
48 decoded_ser = roundtrip(ser)
49 assert_series_equal(decoded_ser, ser)
50
51
52 def test_dataframe_roundtrip():
53 df = pd.DataFrame(
54 {
55 'an_int': np.int_([1, 2, 3]),
56 'a_float': np.float64([2.5, 3.5, 4.5]),
57 'a_nan': np.array([np.nan] * 3),
58 'a_minus_inf': np.array([-np.inf] * 3),
59 'an_inf': np.array([np.inf] * 3),
60 'a_str': np.str_('foo'),
61 'date': np.array([np.datetime64('2014-01-01')] * 3, dtype="datetime64[s]"),
62 'date_ns': np.array(
63 [np.datetime64('2014-01-01')] * 3, dtype="datetime64[ns]"
64 ),
65 'timedelta': np.array([np.timedelta64(1, "Y")] * 3, dtype="timedelta64[Y]"),
66 'complex': np.complex128([1 - 2j, 2 - 1.2j, 3 - 1.3j]),
67 # TODO: the following dtypes are not currently supported.
68 # 'object': np.object_([{'a': 'b'}]*3),
69 }
70 )
71 decoded_df = roundtrip(df)
72 assert_frame_equal(decoded_df, df)
73
74
75 def test_dataframe_nested_containers():
76 # adapted from #407
77 a = pd.DataFrame(
78 {"date": ["20220921abc", 20220921.5], "date2": [20220921, "20220921"]}
79 )
80 b = roundtrip(a, keys=True)
81 assert a['date'][0] == b['date'][0]
82
83
84 def test_dataframe_mixed_dtypes():
85 # adapted from #358
86 df = pd.DataFrame({'col1': [[1, 2, 3], ['a', 'b', 'c']]})
87 assert isinstance((df['col1'].iloc[0]), list)
88 result = roundtrip(df)
89 assert isinstance((result['col1'].iloc[0]), list)
90
91 # adapted from #457
92 # Create simple data frame of mixed data types
93 df1 = pd.DataFrame(([1, 2], [4, 'foo']))
94 df2 = roundtrip(df1)
95 assert (df1[0] == df2[0]).all()
96
97
98 def test_multindex_dataframe_roundtrip():
99 df = pd.DataFrame(
100 {
101 'idx_lvl0': ['a', 'b', 'c'],
•102 'idx_lvl1': np.int64([1, 1, 2]),
103 'an_int': np.int_([1, 2, 3]),
104 'a_float': np.float64([2.5, 3.5, 4.5]),
105 'a_nan': np.array([np.nan] * 3),
106 'a_minus_inf': np.array([-np.inf] * 3),
107 'an_inf': np.array([np.inf] * 3),
108 'a_str': np.str_('foo'),
109 }
110 )
111 df = df.set_index(['idx_lvl0', 'idx_lvl1'])
112
113 decoded_df = roundtrip(df)
114 assert_frame_equal(decoded_df, df)
115
116
117 def test_dataframe_with_interval_index_roundtrip():
118 df = pd.DataFrame(
119 {'a': [1, 2], 'b': [3, 4]}, index=pd.IntervalIndex.from_breaks([1, 2, 4])
120 )
121
122 decoded_df = roundtrip(df)
123 assert_frame_equal(decoded_df, df)
124
125
126 def test_index_roundtrip():
127 idx = pd.Index(range(5, 10))
128 decoded_idx = roundtrip(idx)
129 assert_index_equal(decoded_idx, idx)
130
131
132 def test_datetime_index_roundtrip():
133 idx = pd.date_range(start='2019-01-01', end='2019-02-01', freq='D')
134 decoded_idx = roundtrip(idx)
135 assert_index_equal(decoded_idx, idx)
136
137
138 def test_ragged_datetime_index_roundtrip():
139 idx = pd.DatetimeIndex(['2019-01-01', '2019-01-02', '2019-01-05'])
140 decoded_idx = roundtrip(idx)
141 assert_index_equal(decoded_idx, idx)
142
143
144 def test_timedelta_index_roundtrip():
145 idx = pd.timedelta_range(start='1 day', periods=4, closed='right')
146 decoded_idx = roundtrip(idx)
147 assert_index_equal(decoded_idx, idx)
148
149
150 def test_period_index_roundtrip():
151 idx = pd.period_range(start='2017-01-01', end='2018-01-01', freq='M')
152 decoded_idx = roundtrip(idx)
153 assert_index_equal(decoded_idx, idx)
154
155
156 def test_int64_index_roundtrip():
157 idx = pd.Index([-1, 0, 3, 4], dtype=np.int64)
158 decoded_idx = roundtrip(idx)
159 assert_index_equal(decoded_idx, idx)
160
161
162 def test_uint64_index_roundtrip():
163 idx = pd.Index([0, 3, 4], dtype=np.uint64)
164 decoded_idx = roundtrip(idx)
165 assert_index_equal(decoded_idx, idx)
166
167
168 def test_float64_index_roundtrip():
169 idx = pd.Index([0.1, 3.7, 4.2], dtype=np.float64)
170 decoded_idx = roundtrip(idx)
171 assert_index_equal(decoded_idx, idx)
172
173
174 def test_interval_index_roundtrip():
175 idx = pd.IntervalIndex.from_breaks(range(5))
176 decoded_idx = roundtrip(idx)
177 assert_index_equal(decoded_idx, idx)
178
179
180 def test_datetime_interval_index_roundtrip():
181 idx = pd.IntervalIndex.from_breaks(pd.date_range('2019-01-01', '2019-01-10'))
182 decoded_idx = roundtrip(idx)
183 assert_index_equal(decoded_idx, idx)
184
185
186 def test_multi_index_roundtrip():
187 idx = pd.MultiIndex.from_product(((1, 2, 3), ('a', 'b')))
188 decoded_idx = roundtrip(idx)
189 assert_index_equal(decoded_idx, idx)
190
191
192 def test_timestamp_roundtrip():
193 obj = pd.Timestamp('2019-01-01')
194 decoded_obj = roundtrip(obj)
195 assert decoded_obj == obj
196
197
198 def test_period_roundtrip():
199 obj = pd.Timestamp('2019-01-01')
200 decoded_obj = roundtrip(obj)
201 assert decoded_obj == obj
202
203
204 def test_interval_roundtrip():
205 obj = pd.Interval(2, 4, closed='left')
206 decoded_obj = roundtrip(obj)
207 assert decoded_obj == obj
208
209
210 def test_b64():
211 """Test the binary encoding"""
212 # array of substantial size is stored as b64
213 a = np.random.rand(20, 10)
214 index = ['Row' + str(i) for i in range(1, a.shape[0] + 1)]
215 columns = ['Col' + str(i) for i in range(1, a.shape[1] + 1)]
216 df = pd.DataFrame(a, index=index, columns=columns)
217 decoded_df = roundtrip(df)
218 assert_frame_equal(decoded_df, df)
219
220
221 def test_series_list_index():
222 """Test pandas using series with a list index"""
223 expect = pd.Series(0, index=[1, 2, 3])
224 actual = roundtrip(expect)
225
226 assert expect.values[0] == actual.values[0]
227 assert 0 == actual.values[0]
228
229 assert expect.index[0] == actual.index[0]
230 assert expect.index[1] == actual.index[1]
231 assert expect.index[2] == actual.index[2]
232
233
234 def test_series_multi_index():
235 """Test pandas using series with a multi-index"""
236 expect = pd.Series(0, index=[[1], [2], [3]])
237 actual = roundtrip(expect)
238
239 assert expect.values[0] == actual.values[0]
240 assert 0 == actual.values[0]
241
242 assert expect.index[0] == actual.index[0]
243 assert expect.index[0][0] == actual.index[0][0]
244 assert expect.index[0][1] == actual.index[0][1]
245 assert expect.index[0][2] == actual.index[0][2]
246
247
248 def test_series_multi_index_strings():
249 """Test multi-index with strings"""
250 lets = ['A', 'B', 'C']
251 nums = ['1', '2', '3']
252 midx = pd.MultiIndex.from_product([lets, nums])
253 expect = pd.Series(0, index=midx)
254 actual = roundtrip(expect)
255
256 assert expect.values[0] == actual.values[0]
257 assert 0 == actual.values[0]
258
259 assert expect.index[0] == actual.index[0]
260 assert expect.index[1] == actual.index[1]
261 assert expect.index[2] == actual.index[2]
262 assert expect.index[3] == actual.index[3]
263 assert expect.index[4] == actual.index[4]
264 assert expect.index[5] == actual.index[5]
265 assert expect.index[6] == actual.index[6]
266 assert expect.index[7] == actual.index[7]
267 assert expect.index[8] == actual.index[8]
268
269 assert ('A', '1') == actual.index[0]
270 assert ('A', '2') == actual.index[1]
271 assert ('A', '3') == actual.index[2]
272 assert ('B', '1') == actual.index[3]
273 assert ('B', '2') == actual.index[4]
274 assert ('B', '3') == actual.index[5]
275 assert ('C', '1') == actual.index[6]
276 assert ('C', '2') == actual.index[7]
277 assert ('C', '3') == actual.index[8]
278
279
280 def test_dataframe_with_timedelta64_dtype():
281 data_frame = pd.DataFrame(
282 {
283 'Start': [
284 '2020/12/14 00:00:01',
285 '2020/12/14 00:00:04',
286 '2020/12/14 00:00:06',
287 ],
288 'End': [
289 '2020/12/14 00:00:04',
290 '2020/12/14 00:00:06',
291 '2020/12/14 00:00:09',
292 ],
293 }
294 )
295 data_frame['Start'] = pd.to_datetime(data_frame['Start'])
296 data_frame['End'] = pd.to_datetime(data_frame['End'])
297 data_frame['Duration'] = data_frame['End'] - data_frame['Start']
298
299 encoded = jsonpickle.encode(data_frame)
300 actual = jsonpickle.decode(encoded)
301
302 assert isinstance(actual, pd.DataFrame)
303 assert data_frame['Start'][0] == actual['Start'][0]
304 assert data_frame['Start'][1] == actual['Start'][1]
305 assert data_frame['Start'][2] == actual['Start'][2]
306 assert data_frame['End'][0] == actual['End'][0]
307 assert data_frame['End'][1] == actual['End'][1]
308 assert data_frame['End'][2] == actual['End'][2]
309 assert isinstance(actual['Duration'][0], datetime.timedelta)
310 assert isinstance(actual['Duration'][1], datetime.timedelta)
311 assert isinstance(actual['Duration'][2], datetime.timedelta)
312 assert data_frame['Duration'][0] == actual['Duration'][0]
313 assert data_frame['Duration'][1] == actual['Duration'][1]
314 assert data_frame['Duration'][2] == actual['Duration'][2]
315
316
317 def test_multilevel_columns():
318 iterables = [['inj', 'prod'], ['hourly', 'cumulative']]
319 names = ['first', 'second']
320 # transform it to tuples
321 columns = pd.MultiIndex.from_product(iterables, names=names)
322 # build a multi-index from it
323 data_frame = pd.DataFrame(
324 np.random.randn(3, 4), index=['A', 'B', 'C'], columns=columns
325 )
326 encoded = jsonpickle.encode(data_frame)
327 cloned_data_frame = jsonpickle.decode(encoded)
328 assert isinstance(cloned_data_frame, pd.DataFrame)
329 assert data_frame.columns.names == cloned_data_frame.columns.names
330 assert_frame_equal(data_frame, cloned_data_frame)
331 assert names == cloned_data_frame.columns.names