Skip to content

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

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

Merged
merged 19 commits into from
Feb 23, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
32 changes: 27 additions & 5 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,
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 @@ -277,9 +277,24 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True,
'table' as an allowed value for the ``orient`` argument

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,
dtype : boolean or dict
If True, infer dtypes; if a dict of column to dtype, then use those;
if False, then don't infer dtypes at all, applies only to the data.

The allowed and default values depend on the value of the `orient`
parameter:

- if ``orient != 'table'``:

- allowed ``dtype`` values are True, False or a dict
- default is True

- if ``orient == 'table'``:

- allowed and default ``dtype`` is False

.. versionchanged:: 0.24.2 set default False for ``orient='table'``

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 +423,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 and orient == 'table':
raise ValueError("'dtype' is only valid when 'orient' is not 'table'")

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 +618,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

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
6 changes: 6 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,12 @@ def test_data_frame_size_after_to_json(self):

assert size_before == size_after

def test_from_json_to_json_table_dtypes(self):
expected = pd.DataFrame({'a': [1, 2], 'b': [3., 4.], 'c': ['5', '6']})
dfjson = expected.to_json(orient='table')
result = pd.read_json(dfjson, orient='table')
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