Skip to content

Commit 499bf77

Browse files
committed
BUG:#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 499bf77

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
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/_table_schema.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
)
2222
from pandas.core.dtypes.dtypes import CategoricalDtype
2323

24-
from pandas import DataFrame
24+
from pandas import DataFrame, MultiIndex
2525
import pandas.core.common as com
2626

2727
loads = json.loads
@@ -230,6 +230,10 @@ def build_table_schema(data, index=True, primary_key=None, version=True):
230230
'pandas_version': '0.20.0',
231231
'primaryKey': ['idx']}
232232
"""
233+
234+
if data.index.nlevels == 1 and isinstance(data.index, MultiIndex):
235+
data.index = data.index.get_level_values(0)
236+
233237
if index is True:
234238
data = set_default_names(data)
235239

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)