File: pandas_test.py

package info (click to toggle)
jsonpickle 3.0.0%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,184 kB
  • sloc: python: 6,088; javascript: 654; makefile: 90; sh: 17
file content (312 lines) | stat: -rw-r--r-- 9,730 bytes parent folder | download
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
311
312
from __future__ import absolute_import, division, unicode_literals

import datetime

import pytest

try:
    import numpy as np
    import pandas as pd
    from pandas.testing import (
        assert_frame_equal,
        assert_index_equal,
        assert_series_equal,
    )
except ImportError:
    pytest.skip('numpy is not available', allow_module_level=True)


import jsonpickle
import jsonpickle.ext.pandas


@pytest.fixture(scope='module', autouse=True)
def pandas_extension():
    """Initialize the numpy extension for this test module"""
    jsonpickle.ext.pandas.register_handlers()
    yield  # control to the test function.
    jsonpickle.ext.pandas.unregister_handlers()


def roundtrip(obj):
    return jsonpickle.decode(jsonpickle.encode(obj))


def test_series_roundtrip():
    ser = pd.Series(
        {
            'an_int': np.int_(1),
            'a_float': np.float_(2.5),
            'a_nan': np.nan,
            'a_minus_inf': -np.inf,
            'an_inf': np.inf,
            'a_str': np.str_('foo'),
            'a_unicode': np.unicode_('bar'),
            'date': np.datetime64('2014-01-01'),
            'complex': np.complex_(1 - 2j),
            # TODO: the following dtypes are not currently supported.
            # 'object': np.object_({'a': 'b'}),
        }
    )
    decoded_ser = roundtrip(ser)
    assert_series_equal(decoded_ser, ser)


def test_dataframe_roundtrip():
    df = pd.DataFrame(
        {
            'an_int': np.int_([1, 2, 3]),
            'a_float': np.float_([2.5, 3.5, 4.5]),
            'a_nan': np.array([np.nan] * 3),
            'a_minus_inf': np.array([-np.inf] * 3),
            'an_inf': np.array([np.inf] * 3),
            'a_str': np.str_('foo'),
            'a_unicode': np.unicode_('bar'),
            'date': np.array([np.datetime64('2014-01-01')] * 3),
            'complex': np.complex_([1 - 2j, 2 - 1.2j, 3 - 1.3j]),
            # TODO: the following dtypes are not currently supported.
            # 'object': np.object_([{'a': 'b'}]*3),
        }
    )
    decoded_df = roundtrip(df)
    assert_frame_equal(decoded_df, df)


def test_multindex_dataframe_roundtrip():
    df = pd.DataFrame(
        {
            'idx_lvl0': ['a', 'b', 'c'],
            'idx_lvl1': np.int_([1, 1, 2]),
            'an_int': np.int_([1, 2, 3]),
            'a_float': np.float_([2.5, 3.5, 4.5]),
            'a_nan': np.array([np.nan] * 3),
            'a_minus_inf': np.array([-np.inf] * 3),
            'an_inf': np.array([np.inf] * 3),
            'a_str': np.str_('foo'),
            'a_unicode': np.unicode_('bar'),
        }
    )
    df = df.set_index(['idx_lvl0', 'idx_lvl1'])

    decoded_df = roundtrip(df)
    assert_frame_equal(decoded_df, df)


def test_dataframe_with_interval_index_roundtrip():
    df = pd.DataFrame(
        {'a': [1, 2], 'b': [3, 4]}, index=pd.IntervalIndex.from_breaks([1, 2, 4])
    )

    decoded_df = roundtrip(df)
    assert_frame_equal(decoded_df, df)


def test_index_roundtrip():
    idx = pd.Index(range(5, 10))
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_datetime_index_roundtrip():
    idx = pd.date_range(start='2019-01-01', end='2019-02-01', freq='D')
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_ragged_datetime_index_roundtrip():
    idx = pd.DatetimeIndex(['2019-01-01', '2019-01-02', '2019-01-05'])
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_timedelta_index_roundtrip():
    idx = pd.timedelta_range(start='1 day', periods=4, closed='right')
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_period_index_roundtrip():
    idx = pd.period_range(start='2017-01-01', end='2018-01-01', freq='M')
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_int64_index_roundtrip():
    idx = pd.Index([-1, 0, 3, 4], dtype=np.int64)
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_uint64_index_roundtrip():
    idx = pd.Index([0, 3, 4], dtype=np.uint64)
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_float64_index_roundtrip():
    idx = pd.Index([0.1, 3.7, 4.2], dtype=np.float64)
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_interval_index_roundtrip():
    idx = pd.IntervalIndex.from_breaks(range(5))
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_datetime_interval_index_roundtrip():
    idx = pd.IntervalIndex.from_breaks(pd.date_range('2019-01-01', '2019-01-10'))
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_multi_index_roundtrip():
    idx = pd.MultiIndex.from_product(((1, 2, 3), ('a', 'b')))
    decoded_idx = roundtrip(idx)
    assert_index_equal(decoded_idx, idx)


def test_timestamp_roundtrip():
    obj = pd.Timestamp('2019-01-01')
    decoded_obj = roundtrip(obj)
    assert decoded_obj == obj


def test_period_roundtrip():
    obj = pd.Timestamp('2019-01-01')
    decoded_obj = roundtrip(obj)
    assert decoded_obj == obj


def test_interval_roundtrip():
    obj = pd.Interval(2, 4, closed=str('left'))
    decoded_obj = roundtrip(obj)
    assert decoded_obj == obj


def test_b64():
    """Test the binary encoding"""
    # array of substantial size is stored as b64
    a = np.random.rand(20, 10)
    index = ['Row' + str(i) for i in range(1, a.shape[0] + 1)]
    columns = ['Col' + str(i) for i in range(1, a.shape[1] + 1)]
    df = pd.DataFrame(a, index=index, columns=columns)
    decoded_df = roundtrip(df)
    assert_frame_equal(decoded_df, df)


def test_series_list_index():
    """Test pandas using series with a list index"""
    expect = pd.Series(0, index=[1, 2, 3])
    actual = roundtrip(expect)

    assert expect.values[0] == actual.values[0]
    assert 0 == actual.values[0]

    assert expect.index[0] == actual.index[0]
    assert expect.index[1] == actual.index[1]
    assert expect.index[2] == actual.index[2]


def test_series_multi_index():
    """Test pandas using series with a multi-index"""
    expect = pd.Series(0, index=[[1], [2], [3]])
    actual = roundtrip(expect)

    assert expect.values[0] == actual.values[0]
    assert 0 == actual.values[0]

    assert expect.index[0] == actual.index[0]
    assert expect.index[0][0] == actual.index[0][0]
    assert expect.index[0][1] == actual.index[0][1]
    assert expect.index[0][2] == actual.index[0][2]


def test_series_multi_index_strings():
    """Test multi-index with strings"""
    lets = ['A', 'B', 'C']
    nums = ['1', '2', '3']
    midx = pd.MultiIndex.from_product([lets, nums])
    expect = pd.Series(0, index=midx)
    actual = roundtrip(expect)

    assert expect.values[0] == actual.values[0]
    assert 0 == actual.values[0]

    assert expect.index[0] == actual.index[0]
    assert expect.index[1] == actual.index[1]
    assert expect.index[2] == actual.index[2]
    assert expect.index[3] == actual.index[3]
    assert expect.index[4] == actual.index[4]
    assert expect.index[5] == actual.index[5]
    assert expect.index[6] == actual.index[6]
    assert expect.index[7] == actual.index[7]
    assert expect.index[8] == actual.index[8]

    assert ('A', '1') == actual.index[0]
    assert ('A', '2') == actual.index[1]
    assert ('A', '3') == actual.index[2]
    assert ('B', '1') == actual.index[3]
    assert ('B', '2') == actual.index[4]
    assert ('B', '3') == actual.index[5]
    assert ('C', '1') == actual.index[6]
    assert ('C', '2') == actual.index[7]
    assert ('C', '3') == actual.index[8]


def test_dataframe_with_timedelta64_dtype():
    data_frame = pd.DataFrame(
        {
            'Start': [
                '2020/12/14 00:00:01',
                '2020/12/14 00:00:04',
                '2020/12/14 00:00:06',
            ],
            'End': [
                '2020/12/14 00:00:04',
                '2020/12/14 00:00:06',
                '2020/12/14 00:00:09',
            ],
        }
    )
    data_frame['Start'] = pd.to_datetime(data_frame['Start'])
    data_frame['End'] = pd.to_datetime(data_frame['End'])
    data_frame['Duration'] = data_frame['End'] - data_frame['Start']

    encoded = jsonpickle.encode(data_frame)
    actual = jsonpickle.decode(encoded)

    assert isinstance(actual, pd.DataFrame)
    assert data_frame['Start'][0] == actual['Start'][0]
    assert data_frame['Start'][1] == actual['Start'][1]
    assert data_frame['Start'][2] == actual['Start'][2]
    assert data_frame['End'][0] == actual['End'][0]
    assert data_frame['End'][1] == actual['End'][1]
    assert data_frame['End'][2] == actual['End'][2]
    assert isinstance(actual['Duration'][0], datetime.timedelta)
    assert isinstance(actual['Duration'][1], datetime.timedelta)
    assert isinstance(actual['Duration'][2], datetime.timedelta)
    assert data_frame['Duration'][0] == actual['Duration'][0]
    assert data_frame['Duration'][1] == actual['Duration'][1]
    assert data_frame['Duration'][2] == actual['Duration'][2]


def test_multilevel_columns():
    iterables = [['inj', 'prod'], ['hourly', 'cumulative']]
    names = ['first', 'second']
    # transform it to tuples
    columns = pd.MultiIndex.from_product(iterables, names=names)
    # build a multi-index from it
    data_frame = pd.DataFrame(
        np.random.randn(3, 4), index=['A', 'B', 'C'], columns=columns
    )
    encoded = jsonpickle.encode(data_frame)
    cloned_data_frame = jsonpickle.decode(encoded)
    assert isinstance(cloned_data_frame, pd.DataFrame)
    assert data_frame.columns.names == cloned_data_frame.columns.names
    assert_frame_equal(data_frame, cloned_data_frame)


if __name__ == '__main__':
    pytest.main([__file__])