Skip to content

Commit 415012f

Browse files
Pyry Kovanenjreback
Pyry Kovanen
authored andcommitted
BUG: Fix empty Data frames to JSON round-trippable back to data frames (#21318)
1 parent 324b324 commit 415012f

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

doc/source/whatsnew/v0.23.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ Bug Fixes
122122
- Bug in IO methods specifying ``compression='zip'`` which produced uncompressed zip archives (:issue:`17778`, :issue:`21144`)
123123
- Bug in :meth:`DataFrame.to_stata` which prevented exporting DataFrames to buffers and most file-like objects (:issue:`21041`)
124124
- Bug in :meth:`read_stata` and :class:`StataReader` which did not correctly decode utf-8 strings on Python 3 from Stata 14 files (dta version 118) (:issue:`21244`)
125+
- Bug in IO JSON :func:`read_json` reading empty JSON schema with ``orient='table'`` back to :class:`DataFrame` caused an error (:issue:`21287`)
125126

126127
**Reshaping**
127128

pandas/io/json/table_schema.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ def parse_table_schema(json, precise_float):
296296
"""
297297
table = loads(json, precise_float=precise_float)
298298
col_order = [field['name'] for field in table['schema']['fields']]
299-
df = DataFrame(table['data'])[col_order]
299+
df = DataFrame(table['data'], columns=col_order)[col_order]
300300

301301
dtypes = {field['name']: convert_json_field_to_pandas_type(field)
302302
for field in table['schema']['fields']}

pandas/tests/io/json/test_json_table_schema.py

+13
Original file line numberDiff line numberDiff line change
@@ -560,3 +560,16 @@ def test_multiindex(self, index_names):
560560
out = df.to_json(orient="table")
561561
result = pd.read_json(out, orient="table")
562562
tm.assert_frame_equal(df, result)
563+
564+
@pytest.mark.parametrize("strict_check", [
565+
pytest.param(True, marks=pytest.mark.xfail), False])
566+
def test_empty_frame_roundtrip(self, strict_check):
567+
# GH 21287
568+
df = pd.DataFrame([], columns=['a', 'b', 'c'])
569+
expected = df.copy()
570+
out = df.to_json(orient='table')
571+
result = pd.read_json(out, orient='table')
572+
# TODO: When DF coercion issue (#21345) is resolved tighten type checks
573+
tm.assert_frame_equal(expected, result,
574+
check_dtype=strict_check,
575+
check_index_type=strict_check)

0 commit comments

Comments
 (0)