Skip to content

Commit 3197472

Browse files
committed
BUG:pandas-dev#29928 Fix to_json output with 'table' orient for single level MultiIndex.
Index field name in written json was incorrect, so applying read_json resulted in NaN index values. Dataframe to_json with 'table' orient now treats single level MultiIndex like single Index.
1 parent 55e8891 commit 3197472

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -802,6 +802,7 @@ I/O
802802
- Bug in :meth:`~DataFrame.read_feather` was raising an `ArrowIOError` when reading an s3 or http file path (:issue:`29055`)
803803
- Bug in :meth:`read_parquet` was raising a ``FileNotFoundError`` when passed an s3 directory path. (:issue:`26388`)
804804
- Bug in :meth:`~DataFrame.to_parquet` was throwing an ``AttributeError`` when writing a partitioned parquet file to s3 (:issue:`27596`)
805+
- Bug in :meth:`~DataFrame.to_json` with 'table' orient was writting wrong index field name for MultiIndex Dataframe with a single level. (:issue:`29928`)
805806

806807
Plotting
807808
^^^^^^^^

pandas/io/json/_json.py

+3
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,9 @@ def __init__(
286286
)
287287
raise ValueError(msg)
288288

289+
if obj.index.nlevels == 1 and isinstance(obj.index, MultiIndex):
290+
obj.index = obj.index.get_level_values(0)
291+
289292
self.schema = build_table_schema(obj, index=self.index)
290293

291294
# NotImplemented on a column MultiIndex

pandas/tests/io/json/test_json_table_schema.py

+17
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,23 @@ def test_to_json_categorical_index(self):
435435

436436
assert result == expected
437437

438+
@pytest.mark.parametrize("name", [None, "foo"])
439+
def test_multiindex_single_level(self, name):
440+
# GH29928
441+
index = pd.Index([1, 2, 3, 4], name=name)
442+
df = pd.DataFrame(
443+
data=[[1, 1], [2, 2], [3, 3], [4, 4]], columns=["A", "B"], index=index
444+
)
445+
expected = df.to_json(orient="table")
446+
447+
index = pd.MultiIndex.from_tuples([(1,), (2,), (3,), (4,)], names=[name])
448+
df = pd.DataFrame(
449+
data=[[1, 1], [2, 2], [3, 3], [4, 4]], columns=["A", "B"], index=index
450+
)
451+
result = df.to_json(orient="table")
452+
453+
assert result == expected
454+
438455
def test_date_format_raises(self):
439456
with pytest.raises(ValueError):
440457
self.df.to_json(orient="table", date_format="epoch")

0 commit comments

Comments
 (0)