Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: Fix type coercion in read_json orient='table' (#21345) #25219

Merged
merged 19 commits into from
Feb 23, 2019
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions pandas/io/json/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ def _write(self, obj, orient, double_precision, ensure_ascii,
return serialized


def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
def read_json(path_or_buf=None, orient=None, typ='frame', dtype=None,
albertvillanova marked this conversation as resolved.
Show resolved Hide resolved
convert_axes=True, convert_dates=True, keep_default_dates=True,
numpy=False, precise_float=False, date_unit=None, encoding=None,
lines=False, chunksize=None, compression='infer'):
Expand Down Expand Up @@ -278,8 +278,14 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,

typ : type of object to recover (series or frame), default 'frame'
dtype : boolean or dict, default True
If True, infer dtypes, if a dict of column to dtype, then use those,
If True, infer dtypes; if a dict of column to dtype, then use those;
jreback marked this conversation as resolved.
Show resolved Hide resolved
if False, then don't infer dtypes at all, applies only to the data.

Not applicable with orient='table'.

.. versionchanged:: 0.25
Not applicable with ``orient='table'``
albertvillanova marked this conversation as resolved.
Show resolved Hide resolved

convert_axes : boolean, default True
Try to convert the axes to the proper dtypes.
convert_dates : boolean, default True
Expand Down Expand Up @@ -408,6 +414,9 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
{"index": "row 2", "col 1": "c", "col 2": "d"}]}'
"""

if dtype is not None and orient == 'table':
raise ValueError("cannot pass both dtype and orient='table'")
jreback marked this conversation as resolved.
Show resolved Hide resolved

compression = _infer_compression(path_or_buf, compression)
filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer(
path_or_buf, encoding=encoding, compression=compression,
Expand Down Expand Up @@ -600,15 +609,19 @@ class Parser(object):
'us': long(31536000000000),
'ns': long(31536000000000000)}

def __init__(self, json, orient, dtype=True, convert_axes=True,
def __init__(self, json, orient, dtype=None, convert_axes=True,
convert_dates=True, keep_default_dates=False, numpy=False,
precise_float=False, date_unit=None):
self.json = json

if orient is None:
orient = self._default_orient

self.orient = orient

albertvillanova marked this conversation as resolved.
Show resolved Hide resolved
if orient == 'table':
dtype = False
if dtype is None:
dtype = True
self.dtype = dtype

if orient == "split":
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/io/json/test_json_table_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,12 +502,12 @@ class TestTableOrientReader(object):
@pytest.mark.parametrize("vals", [
{'ints': [1, 2, 3, 4]},
{'objects': ['a', 'b', 'c', 'd']},
{'objects': ['1', '2', '3', '4']},
{'date_ranges': pd.date_range('2016-01-01', freq='d', periods=4)},
{'categoricals': pd.Series(pd.Categorical(['a', 'b', 'c', 'c']))},
{'ordered_cats': pd.Series(pd.Categorical(['a', 'b', 'c', 'c'],
ordered=True))},
pytest.param({'floats': [1., 2., 3., 4.]},
marks=pytest.mark.xfail),
{'floats': [1., 2., 3., 4.]},
{'floats': [1.1, 2.2, 3.3, 4.4]},
{'bools': [True, False, False, True]}])
def test_read_json_table_orient(self, index_nm, vals, recwarn):
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/io/json/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -1202,6 +1202,22 @@ def test_data_frame_size_after_to_json(self):

assert size_before == size_after

def test_from_json_to_json_table_dtypes(self):
# GH21345
expected = pd.DataFrame({'a': [1, 2], 'b': [3., 4.], 'c': ['5', '6']})
albertvillanova marked this conversation as resolved.
Show resolved Hide resolved
dfjson = expected.to_json(orient='table')
result = pd.read_json(dfjson, orient='table')
assert_frame_equal(result, expected)

@pytest.mark.xfail(raises=ValueError)
albertvillanova marked this conversation as resolved.
Show resolved Hide resolved
@pytest.mark.parametrize('dtype', [True, False, {'b': int, 'c': int}])
def test_error_read_json_table_dtype(self, dtype):
albertvillanova marked this conversation as resolved.
Show resolved Hide resolved
# GH21345
expected = pd.DataFrame({'a': [1, 2], 'b': [3., 4.], 'c': ['5', '6']})
albertvillanova marked this conversation as resolved.
Show resolved Hide resolved
dfjson = expected.to_json(orient='table')
result = pd.read_json(dfjson, orient='table', dtype=dtype)
assert_frame_equal(result, expected)

@pytest.mark.parametrize('data, expected', [
(DataFrame([[1, 2], [4, 5]], columns=['a', 'b']),
{'columns': ['a', 'b'], 'data': [[1, 2], [4, 5]]}),
Expand Down